﻿//tagsinput.js
(function ($) {
  "use strict";

  var defaultOptions = {
    tagClass: function(item) {
      return 'badge badge-info';
    },
    focusClass: 'focus',
    itemValue: function(item) {
      return item ? item.toString() : item;
    },
    itemText: function(item) {
      return this.itemValue(item);
    },
    itemTitle: function(item) {
      return null;
    },
    freeInput: true,
    addOnBlur: true,
    maxTags: undefined,
    maxChars: undefined,
    confirmKeys: [13, 44],
    delimiter: ',',
    delimiterRegex: null,
    cancelConfirmKeysOnEmpty: false,
    onTagExists: function(item, $tag) {
      $tag.hide().fadeIn();
    },
    trimValue: false,
    allowDuplicates: false,
    triggerChange: true
  };

  /**
   * Constructor function
   */
  function TagsInput(element, options) {
    this.isInit = true;
    this.itemsArray = [];

    this.$element = $(element);
	
    //this.$element.hide();
	this.$element.attr("type","hidden");

    this.isSelect = (element.tagName === 'SELECT');
    this.multiple = (this.isSelect && element.hasAttribute('multiple'));
    this.objectItems = options && options.itemValue;
    this.placeholderText = element.hasAttribute('placeholder') ? this.$element.attr('placeholder') : '';
    this.inputSize = Math.max(1, this.placeholderText.length);

    this.$container = $('<div class="tagsinput"></div>');
    this.$input = $('<input type="text" placeholder="' + this.placeholderText + '"/>').appendTo(this.$container);

    this.$element.before(this.$container);

    this.build(options);
    this.isInit = false;
  }

  TagsInput.prototype = {
    constructor: TagsInput,

    /**
     * Adds the given item as a new tag. Pass true to dontPushVal to prevent
     * updating the elements val()
     */
    add: function(item, dontPushVal, options) {
      var self = this;

      if (self.options.maxTags && self.itemsArray.length >= self.options.maxTags)
        return;

      // Ignore falsey values, except false
      if (item !== false && !item)
        return;

      // Trim value
      if (typeof item === "string" && self.options.trimValue) {
        item = $.trim(item);
      }

      // Throw an error when trying to add an object while the itemValue option was not set
      if (typeof item === "object" && !self.objectItems)
        throw("Can't add objects when itemValue option is not set");

      // Ignore strings only containg whitespace
      if (item.toString().match(/^\s*$/))
        return;

      // If SELECT but not multiple, remove current tag
      if (self.isSelect && !self.multiple && self.itemsArray.length > 0)
        self.remove(self.itemsArray[0]);

      if (typeof item === "string" && this.$element[0].tagName === 'INPUT') {
        var delimiter = (self.options.delimiterRegex) ? self.options.delimiterRegex : self.options.delimiter;
        var items = item.split(delimiter);
        if (items.length > 1) {
          for (var i = 0; i < items.length; i++) {
            this.add(items[i], true);
          }

          if (!dontPushVal)
            self.pushVal(self.options.triggerChange);
          return;
        }
      }

      var itemValue = self.options.itemValue(item),
          itemText = self.options.itemText(item),
          tagClass = self.options.tagClass(item),
          itemTitle = self.options.itemTitle(item);

      // Ignore items allready added
      var existing = $.grep(self.itemsArray, function(item) { return self.options.itemValue(item) === itemValue; } )[0];
      if (existing && !self.options.allowDuplicates) {
        // Invoke onTagExists
        if (self.options.onTagExists) {
          var $existingTag = $(".badge", self.$container).filter(function() { return $(this).data("item") === existing; });
          self.options.onTagExists(item, $existingTag);
        }
        return;
      }

      // if length greater than limit
      if (self.items().toString().length + item.length + 1 > self.options.maxInputLength)
        return;

      // raise beforeItemAdd arg
      var beforeItemAddEvent = $.Event('beforeItemAdd', { item: item, cancel: false, options: options});
      self.$element.trigger(beforeItemAddEvent);
      if (beforeItemAddEvent.cancel)
        return;

      // register item in internal array and map
      self.itemsArray.push(item);

      // add a tag element

      var $tag = $('<span class="badge ' + htmlEncode(tagClass) + (itemTitle !== null ? ('" title="' + itemTitle) : '') + '">' + htmlEncode(itemText) + '<span data-role="remove"></span></span>');
      $tag.data('item', item);
      self.findInputWrapper().before($tag);
      $tag.after(' ');

      // Check to see if the tag exists in its raw or uri-encoded form
      var optionExists = (
        $('option[value="' + encodeURIComponent(itemValue) + '"]', self.$element).length ||
        $('option[value="' + htmlEncode(itemValue) + '"]', self.$element).length
      );

      // add <option /> if item represents a value not present in one of the <select />'s options
      if (self.isSelect && !optionExists) {
        var $option = $('<option selected>' + htmlEncode(itemText) + '</option>');
        $option.data('item', item);
        $option.attr('value', itemValue);
        self.$element.append($option);
      }

      if (!dontPushVal)
        self.pushVal(self.options.triggerChange);

      // Add class when reached maxTags
      if (self.options.maxTags === self.itemsArray.length || self.items().toString().length === self.options.maxInputLength)
        self.$container.addClass('bootstrap-tagsinput-max');

      // If using typeahead, once the tag has been added, clear the typeahead value so it does not stick around in the input.
      if ($('.typeahead, .twitter-typeahead', self.$container).length) {
        self.$input.typeahead('val', '');
      }

      if (this.isInit) {
        self.$element.trigger($.Event('itemAddedOnInit', { item: item, options: options }));
      } else {
        self.$element.trigger($.Event('itemAdded', { item: item, options: options }));
      }
    },

    /**
     * Removes the given item. Pass true to dontPushVal to prevent updating the
     * elements val()
     */
    remove: function(item, dontPushVal, options) {
      var self = this;

      if (self.objectItems) {
        if (typeof item === "object")
          item = $.grep(self.itemsArray, function(other) { return self.options.itemValue(other) ==  self.options.itemValue(item); } );
        else
          item = $.grep(self.itemsArray, function(other) { return self.options.itemValue(other) ==  item; } );

        item = item[item.length-1];
      }

      if (item) {
        var beforeItemRemoveEvent = $.Event('beforeItemRemove', { item: item, cancel: false, options: options });
        self.$element.trigger(beforeItemRemoveEvent);
        if (beforeItemRemoveEvent.cancel)
          return;

        $('.badge', self.$container).filter(function() { return $(this).data('item') === item; }).remove();
        $('option', self.$element).filter(function() { return $(this).data('item') === item; }).remove();
        if($.inArray(item, self.itemsArray) !== -1)
          self.itemsArray.splice($.inArray(item, self.itemsArray), 1);
      }

      if (!dontPushVal)
        self.pushVal(self.options.triggerChange);

      // Remove class when reached maxTags
      if (self.options.maxTags > self.itemsArray.length)
        self.$container.removeClass('bootstrap-tagsinput-max');

      self.$element.trigger($.Event('itemRemoved',  { item: item, options: options }));
    },

    /**
     * Removes all items
     */
    removeAll: function() {
      var self = this;

      $('.badge', self.$container).remove();
      $('option', self.$element).remove();

      while(self.itemsArray.length > 0)
        self.itemsArray.pop();

      self.pushVal(self.options.triggerChange);
    },

    /**
     * Refreshes the tags so they match the text/value of their corresponding
     * item.
     */
    refresh: function() {
      var self = this;
      $('.badge', self.$container).each(function() {
        var $tag = $(this),
            item = $tag.data('item'),
            itemValue = self.options.itemValue(item),
            itemText = self.options.itemText(item),
            tagClass = self.options.tagClass(item);

          // Update tag's class and inner text
          $tag.attr('class', null);
          $tag.addClass('badge ' + htmlEncode(tagClass));
          $tag.contents().filter(function() {
            return this.nodeType == 3;
          })[0].nodeValue = htmlEncode(itemText);

          if (self.isSelect) {
            var option = $('option', self.$element).filter(function() { return $(this).data('item') === item; });
            option.attr('value', itemValue);
          }
      });
    },

    /**
     * Returns the items added as tags
     */
    items: function() {
      return this.itemsArray;
    },

    /**
     * Assembly value by retrieving the value of each item, and set it on the
     * element.
     */
    pushVal: function() {
      var self = this,
          val = $.map(self.items(), function(item) {
            return self.options.itemValue(item).toString();
          });

      //self.$element.val(val, true);
	  self.$element.attr("value",val);

      if (self.options.triggerChange)
        self.$element.trigger('change');
    },

    /**
     * Initializes the tags input behaviour on the element
     */
    build: function(options) {
      var self = this;

      self.options = $.extend({}, defaultOptions, options);
      // When itemValue is set, freeInput should always be false
      if (self.objectItems)
        self.options.freeInput = false;

      makeOptionItemFunction(self.options, 'itemValue');
      makeOptionItemFunction(self.options, 'itemText');
      makeOptionFunction(self.options, 'tagClass');

      // Typeahead Bootstrap version 2.3.2
      if (self.options.typeahead) {
        var typeahead = self.options.typeahead || {};

        makeOptionFunction(typeahead, 'source');

        self.$input.typeahead($.extend({}, typeahead, {
          source: function (query, process) {
            function processItems(items) {
              var texts = [];

              for (var i = 0; i < items.length; i++) {
                var text = self.options.itemText(items[i]);
                map[text] = items[i];
                texts.push(text);
              }
              process(texts);
            }

            this.map = {};
            var map = this.map,
                data = typeahead.source(query);

            if ($.isFunction(data.success)) {
              // support for Angular callbacks
              data.success(processItems);
            } else if ($.isFunction(data.then)) {
              // support for Angular promises
              data.then(processItems);
            } else {
              // support for functions and jquery promises
              $.when(data)
               .then(processItems);
            }
          },
          updater: function (text) {
            self.add(this.map[text]);
            return this.map[text];
          },
          matcher: function (text) {
            return (text.toLowerCase().indexOf(this.query.trim().toLowerCase()) !== -1);
          },
          sorter: function (texts) {
            return texts.sort();
          },
          highlighter: function (text) {
            var regex = new RegExp( '(' + this.query + ')', 'gi' );
            return text.replace( regex, "<strong>$1</strong>" );
          }
        }));
      }

      // typeahead.js
      if (self.options.typeaheadjs) {
        // Determine if main configurations were passed or simply a dataset
        var typeaheadjs = self.options.typeaheadjs;
        if (!$.isArray(typeaheadjs)) {
            typeaheadjs = [null, typeaheadjs];
        }

        $.fn.typeahead.apply(self.$input, typeaheadjs).on('typeahead:selected', $.proxy(function (obj, datum, name) {
          var index = 0;
          typeaheadjs.some(function(dataset, _index) {
            if (dataset.name === name) {
              index = _index;
              return true;
            }
            return false;
          });

          // @TODO Dep: https://github.com/corejavascript/typeahead.js/issues/89
          if (typeaheadjs[index].valueKey) {
            self.add(datum[typeaheadjs[index].valueKey]);
          } else {
            self.add(datum);
          }

          self.$input.typeahead('val', '');
        }, self));
      }

      self.$container.on('click', $.proxy(function(event) {
        if (! self.$element.attr('disabled')) {
          self.$input.removeAttr('disabled');
        }
        self.$input.focus();
      }, self));

        if (self.options.addOnBlur && self.options.freeInput) {
          self.$input.on('focusout', $.proxy(function(event) {
              // HACK: only process on focusout when no typeahead opened, to
              //       avoid adding the typeahead text as tag
              if ($('.typeahead, .twitter-typeahead', self.$container).length === 0) {
                self.add(self.$input.val());
                self.$input.val('');
              }
          }, self));
        }

      // Toggle the 'focus' css class on the container when it has focus
      self.$container.on({
        focusin: function() {
          self.$container.addClass(self.options.focusClass);
        },
        focusout: function() {
          self.$container.removeClass(self.options.focusClass);
        },
      });

      self.$container.on('keydown', 'input', $.proxy(function(event) {
        var $input = $(event.target),
            $inputWrapper = self.findInputWrapper();

        if (self.$element.attr('disabled')) {
          self.$input.attr('disabled', 'disabled');
          return;
        }

        switch (event.which) {
          // BACKSPACE
          case 8:
            if (doGetCaretPosition($input[0]) === 0) {
              var prev = $inputWrapper.prev();
              if (prev.length) {
                self.remove(prev.data('item'));
              }
            }
            break;

          // DELETE
          case 46:
            if (doGetCaretPosition($input[0]) === 0) {
              var next = $inputWrapper.next();
              if (next.length) {
                self.remove(next.data('item'));
              }
            }
            break;

          // LEFT ARROW
          case 37:
            // Try to move the input before the previous tag
            var $prevTag = $inputWrapper.prev();
            if ($input.val().length === 0 && $prevTag[0]) {
              $prevTag.before($inputWrapper);
              $input.focus();
            }
            break;
          // RIGHT ARROW
          case 39:
            // Try to move the input after the next tag
            var $nextTag = $inputWrapper.next();
            if ($input.val().length === 0 && $nextTag[0]) {
              $nextTag.after($inputWrapper);
              $input.focus();
            }
            break;
         default:
             // ignore
         }

        // Reset internal input's size
        var textLength = $input.val().length,
            wordSpace = Math.ceil(textLength / 5),
            size = textLength + wordSpace + 1;
        $input.attr('size', Math.max(this.inputSize, size));
      }, self));

      self.$container.on('keypress', 'input', $.proxy(function(event) {
         var $input = $(event.target);

         if (self.$element.attr('disabled')) {
            self.$input.attr('disabled', 'disabled');
            return;
         }

         var text = $input.val(),
         maxLengthReached = self.options.maxChars && text.length >= self.options.maxChars;
         if (self.options.freeInput && (keyCombinationInList(event, self.options.confirmKeys) || maxLengthReached)) {
            // Only attempt to add a tag if there is data in the field
            if (text.length !== 0) {
               self.add(maxLengthReached ? text.substr(0, self.options.maxChars) : text);
               $input.val('');
            }

            // If the field is empty, let the event triggered fire as usual
            if (self.options.cancelConfirmKeysOnEmpty === false) {
                event.preventDefault();
            }
         }

         // Reset internal input's size
         var textLength = $input.val().length,
            wordSpace = Math.ceil(textLength / 5),
            size = textLength + wordSpace + 1;
         $input.attr('size', Math.max(this.inputSize, size));
      }, self));

      // Remove icon clicked
      self.$container.on('click', '[data-role=remove]', $.proxy(function(event) {
        if (self.$element.attr('disabled')) {
          return;
        }
        self.remove($(event.target).closest('.badge').data('item'));
      }, self));

      // Only add existing value as tags when using strings as tags
      if (self.options.itemValue === defaultOptions.itemValue) {
        if (self.$element[0].tagName === 'INPUT') {
            self.add(self.$element.val());
        } else {
          $('option', self.$element).each(function() {
            self.add($(this).attr('value'), true);
          });
        }
      }
    },

    /**
     * Removes all tagsinput behaviour and unregsiter all event handlers
     */
    destroy: function() {
      var self = this;

      // Unbind events
      self.$container.off('keypress', 'input');
      self.$container.off('click', '[role=remove]');

      self.$container.remove();
      self.$element.removeData('tagsinput');
      self.$element.show();
    },

    /**
     * Sets focus on the tagsinput
     */
    focus: function() {
      this.$input.focus();
    },

    /**
     * Returns the internal input element
     */
    input: function() {
      return this.$input;
    },

    /**
     * Returns the element which is wrapped around the internal input. This
     * is normally the $container, but typeahead.js moves the $input element.
     */
    findInputWrapper: function() {
      var elt = this.$input[0],
          container = this.$container[0];
      while(elt && elt.parentNode !== container)
        elt = elt.parentNode;

      return $(elt);
    }
  };

  /**
   * Register JQuery plugin
   */
  $.fn.tagsinput = function(arg1, arg2, arg3) {
    var results = [];

    this.each(function() {
      var tagsinput = $(this).data('tagsinput');
      // Initialize a new tags input
      if (!tagsinput) {
          tagsinput = new TagsInput(this, arg1);
          $(this).data('tagsinput', tagsinput);
          results.push(tagsinput);

          if (this.tagName === 'SELECT') {
              $('option', $(this)).attr('selected', 'selected');
          }

          // Init tags from $(this).val()
          $(this).val($(this).val());
      } else if (!arg1 && !arg2) {
          // tagsinput already exists
          // no function, trying to init
          results.push(tagsinput);
      } else if(tagsinput[arg1] !== undefined) {
          // Invoke function on existing tags input
            if(tagsinput[arg1].length === 3 && arg3 !== undefined){
               var retVal = tagsinput[arg1](arg2, null, arg3);
            }else{
               var retVal = tagsinput[arg1](arg2);
            }
          if (retVal !== undefined)
              results.push(retVal);
      }
    });

    if ( typeof arg1 == 'string') {
      // Return the results from the invoked function calls
      return results.length > 1 ? results : results[0];
    } else {
      return results;
    }
  };

  $.fn.tagsinput.Constructor = TagsInput;

  /**
   * Most options support both a string or number as well as a function as
   * option value. This function makes sure that the option with the given
   * key in the given options is wrapped in a function
   */
  function makeOptionItemFunction(options, key) {
    if (typeof options[key] !== 'function') {
      var propertyName = options[key];
      options[key] = function(item) { return item[propertyName]; };
    }
  }
  function makeOptionFunction(options, key) {
    if (typeof options[key] !== 'function') {
      var value = options[key];
      options[key] = function() { return value; };
    }
  }
  /**
   * HtmlEncodes the given value
   */
  var htmlEncodeContainer = $('<div />');
  function htmlEncode(value) {
    if (value) {
      return htmlEncodeContainer.text(value).html();
    } else {
      return '';
    }
  }

  /**
   * Returns the position of the caret in the given input field
   * http://flightschool.acylt.com/devnotes/caret-position-woes/
   */
  function doGetCaretPosition(oField) {
    var iCaretPos = 0;
    if (document.selection) {
      oField.focus ();
      var oSel = document.selection.createRange();
      oSel.moveStart ('character', -oField.value.length);
      iCaretPos = oSel.text.length;
    } else if (oField.selectionStart || oField.selectionStart == '0') {
      iCaretPos = oField.selectionStart;
    }
    return (iCaretPos);
  }

  /**
    * Returns boolean indicates whether user has pressed an expected key combination.
    * @param object keyPressEvent: JavaScript event object, refer
    *     http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
    * @param object lookupList: expected key combinations, as in:
    *     [13, {which: 188, shiftKey: true}]
    */
  function keyCombinationInList(keyPressEvent, lookupList) {
      var found = false;
      $.each(lookupList, function (index, keyCombination) {
          if (typeof (keyCombination) === 'number' && keyPressEvent.which === keyCombination) {
              found = true;
              return false;
          }

          if (keyPressEvent.which === keyCombination.which) {
              var alt = !keyCombination.hasOwnProperty('altKey') || keyPressEvent.altKey === keyCombination.altKey,
                  shift = !keyCombination.hasOwnProperty('shiftKey') || keyPressEvent.shiftKey === keyCombination.shiftKey,
                  ctrl = !keyCombination.hasOwnProperty('ctrlKey') || keyPressEvent.ctrlKey === keyCombination.ctrlKey;
              if (alt && shift && ctrl) {
                  found = true;
                  return false;
              }
          }
      });

      return found;
  }

  /**
   * Initialize tagsinput behaviour on inputs and selects which have
   * data-role=tagsinput
   * zmm2113@qq.com 2018.6.24
   */
  $(function() {
    $("input[data-role=tagsinput], select[multiple][data-role=tagsinput]").tagsinput();
  });
})(window.jQuery);

/*签名控件*/

var eSignIn={};
eSignIn.listen=function()
{	
	if(!this.canvas)return;
	var painting = false;
    var lastPoint = { x: undefined, y: undefined };
	//canvas.width = box.offsetWidth;
     //   canvas.height = 240;

	this.canvas.width=this.canvas.clientWidth;
	this.canvas.height=this.canvas.clientHeight;
	
	//document.title=this.canvas.width  + "::" + this.canvas.offsetHeight;
	
	if (document.body.ontouchstart !== undefined)
	{
		this.canvas.ontouchstart = function (e)
		{
			e.preventDefault();			
			var canvasLeft = e.target.offsetLeft;
			var canvasTop = e.target.offsetTop;
            painting = true;
            var x = e.touches[0].pageX - canvasLeft;// e.changedTouches[0].clientX - canvasLeft;
            var y = e.touches[0].pageY - canvasTop;//  e.changedTouches[0].clientY - canvasTop;
            lastPoint = { "x": x, "y": y };

			
			//document.title= "pageX=" + e.touches[0].pageX + "::" + canvasLeft + "," + "pageY=" +  e.touches[0].pageY + "::" + canvasTop;
            eSignIn.ctx.save();
            eSignIn.ctx.beginPath();
           	eSignIn.ctx.moveTo(e.clientX, e.clientY);
        };
		this.canvas.ontouchmove = function (e)
		{
			e.preventDefault();
			if (painting)
			{
				var canvasLeft =  e.target.offsetLeft;
                var canvasTop =  e.target.offsetTop;				
				//document.title= e.changedTouches[0].clientX  + "::" +  e.changedTouches[0].clientY;
                var x = e.changedTouches[0].pageX - canvasLeft;// e.changedTouches[0].clientX - canvasLeft;
                var y = e.changedTouches[0].pageY - canvasTop; //e.changedTouches[0].clientY - canvasTop;
				//document.title= "pageY=" +  e.changedTouches[0].pageY + "::" + canvasTop;
                var newPoint = { "x": x, "y": y };
                eSignIn.drawLine(lastPoint.x, lastPoint.y, newPoint.x, newPoint.y);
                lastPoint = newPoint;
            }
        };
        this.canvas.ontouchend = function () { painting = false; };
    }
    else
	{

		this.canvas.onmousedown = function (e)
		{		
			var canvasLeft = e.target.getBoundingClientRect().left;// e.target.offsetLeft;
            var canvasTop = e.target.getBoundingClientRect().top;//e.target.offsetTop;
			//document.title = e.target.offsetLeft + "::" + e.target.offsetTop + "::" + e.target.getBoundingClientRect().left ;
            painting = true;
            var x = e.clientX - canvasLeft;
            var y = e.clientY - canvasTop;
            lastPoint = { "x": x, "y": y };
            eSignIn.ctx.save();
        };		
        this.canvas.onmousemove = function (e)
		{
			if (painting)
			{
				//document.title = e.target.offsetLeft + "::" + e.clientX + "::" + e.pageX + "::" + e.offsetX;
				var canvasLeft =  e.target.getBoundingClientRect().left;//;//e.target.offsetLeft;
                var canvasTop =  e.target.getBoundingClientRect().top;////e.target.offsetTop;
				
                var x = e.clientX - canvasLeft;
                var y = e.clientY - canvasTop;
                var newPoint = { "x": x, "y": y };
                eSignIn.drawLine(lastPoint.x, lastPoint.y, newPoint.x, newPoint.y);
                lastPoint = newPoint;
            }
        };
        this.canvas.onmouseup = function () { painting = false; };
        this.canvas.mouseleave = function () { painting = false; };
    }	
};
eSignIn.drawLine=function(x1, y1, x2, y2)
{
	if(!this.canvas)return;	
	this.ctx.lineWidth = this.lineWidth;
    this.ctx.lineCap = "round";
    this.ctx.lineJoin = "round";
    this.ctx.moveTo(x1, y1);
    this.ctx.lineTo(x2, y2);
    this.ctx.stroke();
    this.ctx.closePath();
};
eSignIn.init=function()
{
	var canvas = document.getElementById("esignin");
	if(!canvas)return;	
	this.canvas=canvas;
	this.lineWidth=4;
	this.ctx = canvas.getContext("2d");
	
	var edata=canvas.getAttribute("edata");
	if(edata && edata.length>100)
	{
		var img = new Image;
		img.onload = function(){
      		canvas.getContext("2d").drawImage(img,0,0);
    	};
		img.src = "data:image/png;base64," + edata;		
	}
	this.listen();
};
eSignIn.clear=function()
{
	if(!this.canvas)return;
	this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    this.ctx.beginPath();
};
eSignIn.geturldata=function()
{
	if(!this.canvas)return "";
	return this.canvas.toDataURL("image/png");
};
eSignIn.getdata=function()
{
	var data = eSignIn.geturldata();
	data = data.replace(/^data:image\/(png|jpg);base64,/, "");	
	return data;
};

/*网站管理-开始*/
//根据数据模型加载列
function getColumns(id)
{
	var url=document.location.href;
	url=url.addquerystring("act","getcolumns");
	url=url.addquerystring("mid",id);
	$.ajax({
			type: "get",
			url: url,
			dataType: "json",
			success: function(data)
			{		
				//for(var i=0;i < data.data.length; i++)
				if(data.success=="1")		
				{
					ColumnsJson=data.data;
					$("#fields").html('');
					$.each(data.data, function()
					 {
						 var html='<a href="javascript:;" class="htmltag" onclick="addHtmlTag(\'f4\',\'{' + (this["text"] == '内容连接' ? 'url' : 'data') + ':'+ this["value"] +'('+ this["text"] +')}\');">' + this["text"] + '</a>';
						 $("#fields").append(html);
					 });						
				}
			}
	});
};

function addHtmlTag(id,txt)
{
	var obj=document.getElementById(id);	
	if (obj.selectionStart !== undefined)
	{
		var startPos = obj.selectionStart;
		var endPos = obj.selectionEnd;
        obj.value = obj.value.substring(0, startPos) + txt + obj.value.substring(endPos, obj.value.length);
		obj.focus();
        obj.selectionStart = startPos + txt.length;
        obj.selectionEnd = startPos + txt.length;
	}
	else
	{
		  if(document.selection) 
		  { 		  
		  	 obj.focus();
             var sel = document.selection.createRange();
             sel.text =  txt;
		  }
		  else
		  {
		  	obj.value=[obj.value,txt].join("");
		  }
	}	
};
//Json编辑-添加
function Json_Add(objid)
{
	var obj=$("#" + objid);
	var jsonstr=obj.attr("jsonformat");
	var json = jsonstr.toJson();
	var html='<tr>';
		html+='<td height="30" align="center"><img src="../images/del.png" style="cursor:pointer;" onclick="Json_Delete(this);" /></td>';
		json.foreach(function (e)
		{
			html+='<td><input type="text" name="' + json[e].value + '" value="" style="border:0px;background-color:transparent;width:100%;" /></td>';
		});
		var len= $("#JsonTable tbody > tr").length + 1;
		html+='<td style="cursor:move;">' + len + '</td>';
		html+='</tr>';
		//alert(obj.find("tbody").length);

	//alert(json.length);
	$("#JsonTable tbody").append(html);
	
	var	tb=new eDataTable("JsonTable",1);
	
	
};
//Json编辑-删除
function Json_Delete(obj)
{
	if(!confirm('确认要删除吗？')){return;}
	$(obj).parent().parent().remove();
	$("#JsonTable tbody > tr > td:last-child").each(function(index1,obj){
		$(obj).html(1+index1);
	}); 	
};
//Json编辑
function Json_Edit(objid)
{
	
	var obj=$("#" + objid);	
	var jsonstr=obj.attr("jsonformat");
	var json = jsonstr.toJson();
	

	
	var valuestr=obj.val();

	if(valuestr.length>0)
	{
		valuestr=valuestr.replace(/{/g,"{\"");
		valuestr=valuestr.replace(/:/g,"\":\"");
		valuestr=valuestr.replace(/,/g,"\",\"");
		valuestr=valuestr.replace(/}/g,"\"}");
		valuestr=valuestr.replace(/}\",\"{/g,"},{");
		valuestr=valuestr.replace(/\"\"/g,"\"");
	}
	else
	{
		valuestr="[]";
	}
	
	var values=valuestr.toJson();
	//alert(valuestr);
	//alert(json.length);
	json.foreach(function (e)
    {
		//alert(json[e].text + "::" + json[e].value);
    });
	
	var width= 180;

	
	var html='<table id="JsonTable" class="eDataTable" border="0" cellpadding="0" cellspacing="1" width="' + ((json.length*(width-10)) + 35 + 35) +  '" style="margin:10px;">';
	
	html+='<colgroup>';
	html+='<col width="35" />';
	for(var i=0;i<json.length;i++)
	{
		html+='<col width="' + (width-10) + '" />';
	}
	html+='<col width="35" />';
	html+='</colgroup>';	
	html+='<thead>';
	html+='<tr>';
	html+='<td height="30" align="center"><img src="../images/add.png" style="cursor:pointer;" onclick="Json_Add(\'' + objid + '\');" /></td>';
	json.foreach(function (e)
    {
		html+='<td height="30">' + json[e].text + '</td>';
	});
	html+='<td>顺序</td>';
	html+='</tr>';
	html+='</thead>';
	html+='<tbody eMove="true">';
	for(var j=0;j<values.length;j++)
	{
		html+='<tr>';
		html+='<td height="30" align="center"><img src="../images/del.png" style="cursor:pointer;" onclick="Json_Delete(this);" /></td>';
		json.foreach(function (e)
		{
			//html+='<td height="30">' + values[j][json[e].value] + '</td>';
			html+='<td><input type="text" name="' + json[e].value + '" value="' + values[j][json[e].value] + '" style="border:0px;background-color:transparent;width:100%;" /></td>';
		});
		html+='<td style="cursor:move;">' + (j+1) + '</td>';
		html+='</tr>';
	}
	html+='</tbody>';
	html+='</table>';
	layer.open({
      type: 1,
	  title: "选项",
	  scrollbar: false,
      area: [(json.length*width + 20 + 35 + 35 + 20) + 'px', '60%'],
      shadeClose: true, //点击遮罩关闭
	  content: html,
	  btn: ['确定', '取消'],
	  yes: function(index,layero)
	  {
		  var hasnull=false;
		  var _json='[';
		  var _html='';
		 $("#JsonTable tbody tr").each(function(index1,obj){
			if(index1>0){_json+=',';}
			_json+='{';
			$(obj).find("input").each(function(index2,input){
				if(input.value.length==0){hasnull=true;}
				if(index2>0){_json+=',';} 
				if(input.name=="text"){_html += '<span style="display:inline-block;margin-right:6px;border:1px solid #ccc;padding:3px 12px 3px 12px;">' + input.value + '</span>';}
				
				_json += '"' + input.name +  '":"' + input.value.replace(/\"/g,"&quot;") + '"';
			});	
			_json+='}';
		});
		if(hasnull){alert("数据不能为空!");return;}
		_json+=']';
		if(_json.length==0){_json='';}
		
		obj.parent().find("span").remove();
		obj.next().after(_html);
		/*
		var next=obj.next();
		while(next.next()[0].tagName == "SPAN")
		{
			//alert(next.next()[0].tagName);
			next.next().remove();
		}		
		next.after(_html);
		*/


		obj.val(_json);	
		obj.get(0).onblur();
		layer.close(index);
		//alert();
	  },
      cancel: function (index, layero) 
	  {
	  	//arrLayerIndex.pop();
      },
	  success: function (layero, index)
	  {
	  	//arrLayerIndex.push(index);
		var tb=getobj("JsonTable");
		if(tb)
		{
			tb=new eDataTable("JsonTable",1);
			tb.moveRow=function(index,nindex)
			{
				$("#JsonTable tbody > tr > td:last-child").each(function(index1,obj){
					$(obj).html(1+index1);
				}); 
			};		
		}
      }
    });
	
};
function dcond_add(objid)
{
		
	var obj=$("#" + objid);
	var jsonstr=obj.attr("jsonformat");
	var json = jsonstr.toJson();
	

	var html='<tr>';
		html+='<td height="30" align="center"><img src="../images/del.png" style="cursor:pointer;" onclick="dcond_del(this);" /></td>';
		json.foreach(function (e)
		{
			if(json[e].value=="code") //code
			{
				html+='<td><select name="' + json[e].value + '" style="height:24px;">';
				$.each(ColumnsJson, function()				
				{
					html+='<option value="' + this["value"] + '">' +  this["text"]+ '</option>';
				});
				html+='</select></td>';
				
			}
			else if(json[e].value.toLowerCase()=="operator") //operator
			{
				html+='<td><select name="' + json[e].value + '" style="height:24px;">';
				html+='<option value="like">包含</option>';
				html+='<option value="=">等于</option>';
				html+='<option value=">">大于</option>';
				html+='<option value="<">小于</option>';
				html+='<option value="<>">不等于</option>';
				html+='</select></td>';
			}
			else// value
			{
				//html+='<td><input type="text" name="' + json[e].value + '" value="" style="border:1px solid #ccc;padding:3px 5px 3px 5px;background-color:transparent;width:90%;" /></td>';
				
				html+='<td>';			
				html+='<input type="text" name="' + json[e].value + '" value="" style="border:1px solid #ccc;padding:3px 5px 3px 5px;background-color:transparent;width:50%;" />';
				html+='</td>';
			}
			
		});
		html+='</tr>';
		//alert(obj.find("tbody").length);

	//alert(json.length);
	$("#JsonTable tbody").append(html);
	
	var	tb=new eDataTable("JsonTable",1);
};
function dcond_del(obj)
{
	if(!confirm('确认要删除吗？')){return;}
	$(obj).parent().parent().remove();
	$("#JsonTable tbody > tr > td:last-child").each(function(index1,obj){
		$(obj).html(1+index1);
	}); 	
};
function dcond_edit(objid)
{
	
	var obj=$("#" + objid);	
	var jsonstr=obj.attr("jsonformat");
	var json = jsonstr.toJson();
	var valuestr=obj.val();
	
	

	if(valuestr.length>0)
	{
		valuestr=valuestr.replace(/{/g,"{\"");
		valuestr=valuestr.replace(/:/g,"\":\"");
		valuestr=valuestr.replace(/,/g,"\",\"");
		valuestr=valuestr.replace(/}/g,"\"}");
		valuestr=valuestr.replace(/}\",\"{/g,"},{");
		valuestr=valuestr.replace(/\"\"/g,"\"");
	}
	else
	{
		valuestr="[]";
	}	
	var values=valuestr.toJson();
	
	var width= 180;
	var html='<table id="JsonTable" class="eDataTable" border="0" cellpadding="0" cellspacing="0" width="' + ((json.length*(width-10)) + 35 + 35) +  '" style="margin:10px;">';	
	html+='<colgroup>';
	html+='<col width="35" />';
	html+='<col width="' + 150 + '" />';
	html+='<col width="' + 150 + '" />';
	html+='<col width="' + 210 + '" />';
	//for(var i=0;i<json.length;i++)
	//{
		//html+='<col width="' + (width-10) + '" />';
	//}

	html+='</colgroup>';	
	html+='<thead>';
	html+='<tr>';
	html+='<td height="30" align="center"><img src="../images/add.png" style="cursor:pointer;" onclick="dcond_add(\'' + objid + '\');" /></td>';
	json.foreach(function (e)
    {
		html+='<td height="30">' + json[e].text + '</td>';
	});
	html+='</tr>';
	html+='</thead>';
	html+='<tbody eMove="true">';

	for(var j=0;j<values.length;j++)
	{

		html+='<tr>';
		html+='<td height="30" align="center"><img src="../images/del.png" style="cursor:pointer;" onclick="dcond_del(this);" /></td>';
		json.foreach(function (e)
		{
			if(json[e].value.toLowerCase()=="code") //code
			{
				html+='<td><select name="' + json[e].value + '" style="height:24px;">';
				$.each(ColumnsJson, function()
				{
				   	html+='<option value="' + this["value"] + '"'+(values[j][json[e].value].toLowerCase() == this["value"].toLowerCase() ? " selected" : "")+'>' + this["text"] + '</option>';
				});

				html+='</select></td>';
			}
			else if(json[e].value.toLowerCase()=="operator") //operator
			{
				html+='<td><select name="' + json[e].value + '" style="height:24px;">';
				
				html+='<option value="like"'+(values[j][json[e].value].toLowerCase() == "like" ? " selected" : "")+'>包含</option>';
				html+='<option value="="'+(values[j][json[e].value].toLowerCase() == "=" ? " selected" : "")+'>等于</option>';
				html+='<option value=">"'+(values[j][json[e].value].toLowerCase() == ">" ? " selected" : "")+'>大于</option>';
				html+='<option value="<"'+(values[j][json[e].value].toLowerCase() == "<" ? " selected" : "")+'>小于</option>';
				html+='<option value="<>"'+(values[j][json[e].value].toLowerCase() == "<>" ? " selected" : "")+'>不等于</option>';
				html+='</select></td>';
			}
			else// value
			{
				html+='<td>';		
				html+='<input type="text" name="' + json[e].value + '" value="' + values[j][json[e].value] + '" style="border:1px solid #ccc;padding:3px 5px 3px 5px;background-color:transparent;width:50%;" />';
				html+='</td>';
			}
			

		});
		html+='</tr>';

	}

	html+='</tbody>';
	html+='</table>';
	

	
	
	layer.open({
      type: 1,
	  title: "设置条件",
	  scrollbar: false,
      area: [(json.length*width + 20 + 35 + 35 + 20) + 'px', '35%'],
      shadeClose: true, //点击遮罩关闭
	  content: html,
	  btn: ['确定', '取消'],
	  yes: function(index,layero)
	  {

		  var hasnull=false;
		  var _json='[';
		  var _html='';

		 $("#JsonTable tbody tr").each(function(index1,obj){
			if(index1>0)
			{
				_json+=',';

			}
			_json+='{';
			$(obj).find("select,input").each(function(index2,input){
				if(input.name.length==0){return true;}
				if(input.value.length==0 && input.tagName=="INPUT"){hasnull=true;}
				if(index2>0){_json+=',';} 
				//if(input.name=="text"){_html += '<span style="display:inline-block;margin-right:6px;border:1px solid #ccc;padding:3px 12px 3px 12px;">' + input.value + '</span>';}
				
				_json += '"' + input.name +  '":"' + input.value.replace(/'/g,"").replace(/"/g,"") + '"';
				
			});	
			_json+='}';
			_html+= '<span style="display:inline-block;margin-right:10px;border:1px solid #ccc;padding:2px 12px 2px 12px;">';
			_html+= $(obj).find("select:eq(0)").find("option:selected").text() + ' ' + $(obj).find("select:eq(1)").find("option:selected").text() + " 参数" +   $(obj).find("input:eq(0)").val().replace(/'/g,"").replace(/"/g,"") + "的值";
			_html+='</span>';

		});
		if(hasnull){alert("数据不能为空!");return;}
		_json+=']';
		if(_json.length==0){_json='';}
		obj.val(_json);	
		$("#spandcond").html(_html);
		layer.close(index);
	  },
      cancel: function (index, layero) 
	  {
	  	//arrLayerIndex.pop();
      },
	  success: function (layero, index)
	  {
	  	//arrLayerIndex.push(index);

      }
    });
	
};
function order_add(objid)
{
	var obj=$("#" + objid);
	var jsonstr=obj.attr("jsonformat");
	var json = jsonstr.toJson();
	var html='<tr>';
		html+='<td height="30" align="center"><img src="../images/del.png" style="cursor:pointer;" onclick="order_del(this);" /></td>';
		json.foreach(function (e)
		{
			//html+='<td><input type="text" name="' + json[e].value + '" value="" style="border:0px;background-color:transparent;width:100%;" /></td>';
			if(json[e].value=="code")
			{
				//html+='<td>' + json[e].value + '</td>';
				html+='<td><select name="' + json[e].value + '" style="height:24px;">';
				//for(var x=0; x < ColumnsJson.length; x++) //
				$.each(ColumnsJson, function()				
				{
					html+='<option value="' + this["value"] + '">' +  this["text"]+ '</option>';
				});
				html+='</select></td>';
				
			}
			else // value
			{
				html+='<td><select name="' + json[e].value + '" style="height:24px;">';
				html+='<option value="asc">升序</option>';
				html+='<option value="desc">降序</option>';
				html+='</select></td>';
			}
			
		});
		var len= $("#JsonTable tbody > tr").length + 1;
		html+='<td style="cursor:move;">' + len + '</td>';
		html+='</tr>';
		//alert(obj.find("tbody").length);

	//alert(json.length);
	$("#JsonTable tbody").append(html);
	
	var	tb=new eDataTable("JsonTable",1);
};
function order_del(obj)
{
	if(!confirm('确认要删除吗？')){return;}
	$(obj).parent().parent().remove();
	$("#JsonTable tbody > tr > td:last-child").each(function(index1,obj){
		$(obj).html(1+index1);
	}); 	
};
function order_edit(objid)
{
	var obj=$("#" + objid);	
	var jsonstr=obj.attr("jsonformat");
	var json = jsonstr.toJson();
	var valuestr=obj.val();
	
	

	if(valuestr.length>0)
	{
		valuestr=valuestr.replace(/{/g,"{\"");
		valuestr=valuestr.replace(/:/g,"\":\"");
		valuestr=valuestr.replace(/,/g,"\",\"");
		valuestr=valuestr.replace(/}/g,"\"}");
		valuestr=valuestr.replace(/}\",\"{/g,"},{");
		valuestr=valuestr.replace(/\"\"/g,"\"");
	}
	else
	{
		valuestr="[]";
	}	
	var values=valuestr.toJson();
	
	
	
	var width= 180;
	var html='<table id="JsonTable" class="eDataTable" border="0" cellpadding="0" cellspacing="0" width="' + ((json.length*(width-10)) + 35 + 35) +  '" style="margin:10px;">';	
	html+='<colgroup>';
	html+='<col width="35" />';
	for(var i=0;i<json.length;i++)
	{
		html+='<col width="' + (width-10) + '" />';
	}
	html+='<col width="35" />';
	html+='</colgroup>';	
	html+='<thead>';
	html+='<tr>';
	html+='<td height="30" align="center"><img src="../images/add.png" style="cursor:pointer;" onclick="order_add(\'' + objid + '\');" /></td>';
	json.foreach(function (e)
    {
		html+='<td height="30">' + json[e].text + '</td>';
	});
	html+='<td>顺序</td>';
	html+='</tr>';
	html+='</thead>';
	html+='<tbody eMove="true">';

	for(var j=0;j<values.length;j++)
	{
		
		//.toLowerCase()
		
		html+='<tr>';
		html+='<td height="30" align="center"><img src="../images/del.png" style="cursor:pointer;" onclick="order_del(this);" /></td>';
		json.foreach(function (e)
		{

			if(json[e].value.toLowerCase()=="code")
			{
				html+='<td><select name="' + json[e].value + '" style="height:24px;">';
				$.each(ColumnsJson, function()
				{
				   	html+='<option value="' + this["value"] + '"'+(values[j][json[e].value].toLowerCase() == this["value"].toLowerCase() ? " selected" : "")+'>' + this["text"] + '</option>';
				});

				html+='</select></td>';
			}
			else // value
			{
				html+='<td><select name="' + json[e].value + '" style="height:24px;">';
				html+='<option value="asc"'+(values[j][json[e].value].toLowerCase() == "asc" ? " selected" : "")+'>升序</option>';
				html+='<option value="desc"'+(values[j][json[e].value].toLowerCase() == "desc" ? " selected" : "")+'>降序</option>';
				html+='</select></td>';
			}

		});
		html+='<td style="cursor:move;">' + (j+1) + '</td>';
		html+='</tr>';

	}
	html+='</tbody>';
	html+='</table>';

	
	layer.open({
      type: 1,
	  title: "设置排序",
	  scrollbar: false,
      area: [(json.length*width + 20 + 35 + 35 + 20) + 'px', '35%'],
      shadeClose: true, //点击遮罩关闭
	  content: html,
	  btn: ['确定', '取消'],
	  yes: function(index,layero)
	  {

		  var hasnull=false;
		  var _json='[';
		  var _html='';
		  var _orderby='';
		 $("#JsonTable tbody tr").each(function(index1,obj){
			if(index1>0)
			{
				_json+=',';
				_orderby+=',';
			}
			_json+='{';
			$(obj).find("select").each(function(index2,input){
				if(input.value.length==0){hasnull=true;}
				if(index2>0){_json+=',';} 
				//if(input.name=="text"){_html += '<span style="display:inline-block;margin-right:6px;border:1px solid #ccc;padding:3px 12px 3px 12px;">' + input.value + '</span>';}
				
				_json += '"' + input.name +  '":"' + input.value.replace(/\"/g,"&quot;") + '"';
				
			});	
			_json+='}';
			_html+= '<span style="display:inline-block;margin-right:10px;border:1px solid #ccc;padding:2px 12px 2px 12px;">' + $(obj).find("select:eq(0)").find("option:selected").text() + ' -> ' + $(obj).find("select:eq(1)").find("option:selected").text() + '</span>' ;
			_orderby += $(obj).find("select:eq(0)").val() + " " + $(obj).find("select:eq(1)").val();
		});
		if(hasnull){alert("数据不能为空!");return;}
		_json+=']';
		if(_json.length==0){_json='';}
		obj.val(_json);	
		
		$("#fo").val(_orderby);
		
		
		$("#spanorder").html(_html);
		layer.close(index);
	  },
      cancel: function (index, layero) 
	  {
	  	//arrLayerIndex.pop();
      },
	  success: function (layero, index)
	  {
	  	//arrLayerIndex.push(index);

		var tb=getobj("JsonTable");
		if(tb)
		{
			tb=new eDataTable("JsonTable",1);
			tb.moveRow=function(index,nindex)
			{
				$("#JsonTable tbody > tr > td:last-child").each(function(index1,obj){
					$(obj).html(1+index1);
				}); 
			};		
		}

      }
    });
};
function cond_add(objid)
{
		
	var obj=$("#" + objid);
	var jsonstr=obj.attr("jsonformat");
	var json = jsonstr.toJson();
	

	var html='<tr>';
		html+='<td height="30" align="center"><img src="../images/del.png" style="cursor:pointer;" onclick="cond_del(this);" /></td>';
		json.foreach(function (e)
		{
			if(json[e].value=="code") //code
			{
				html+='<td><select name="' + json[e].value + '" style="height:24px;">';
				$.each(ColumnsJson, function()				
				{
					html+='<option value="' + this["value"] + '">' +  this["text"]+ '</option>';
				});
				html+='</select></td>';
				
			}
			else if(json[e].value.toLowerCase()=="operator") //operator
			{
				html+='<td><select name="' + json[e].value + '" style="height:24px;">';
				html+='<option value="like">包含</option>';
				html+='<option value="=">等于</option>';
				html+='<option value=">">大于</option>';
				html+='<option value="<">小于</option>';
				html+='<option value="<>">不等于</option>';
				html+='</select></td>';
			}
			else// value
			{
				//html+='<td><input type="text" name="' + json[e].value + '" value="" style="border:1px solid #ccc;padding:3px 5px 3px 5px;background-color:transparent;width:90%;" /></td>';
				
				html+='<td>';
				html+='<select onchange="cond_change(this);" style="height:24px;">';
				html+='<option value="">输入值</option>';
				html+='<option value="{site:ColumnID(栏目ID)}">栏目ID</option>';
				html+='<option value="{site:ParentColumnID(上级栏目ID)}">上级栏目ID</option>';
				html+='<option value="{site:TopColumnID(上级栏目ID)}">顶级栏目ID</option>';
				html+='<option value="{data:ID(数据ID)}">数据ID</option>';
				html+='<option value="{site:WebCode(网站ID)}">网站ID</option>';			
				html+='<option value="NULL">NULL</option>';
				html+='</select>';				
				html+='<input type="text" name="' + json[e].value + '" value="" style="border:1px solid #ccc;padding:3px 5px 3px 5px;background-color:transparent;width:50%;" />';
				html+='</td>';
			}
			
		});
		var len= $("#JsonTable tbody > tr").length + 1;
		html+='<td style="cursor:move;">' + len + '</td>';
		html+='</tr>';
		//alert(obj.find("tbody").length);

	//alert(json.length);
	$("#JsonTable tbody").append(html);
	
	var	tb=new eDataTable("JsonTable",1);
};
function cond_change(obj)
{
	if($(obj).val().length>0)
	{
		$(obj).next().val($(obj).val());
	}
};
function cond_del(obj)
{
	if(!confirm('确认要删除吗？')){return;}
	$(obj).parent().parent().remove();
	$("#JsonTable tbody > tr > td:last-child").each(function(index1,obj){
		$(obj).html(1+index1);
	}); 	
};
function cond_edit(objid)
{
	
	var obj=$("#" + objid);	
	var jsonstr=obj.attr("jsonformat");
	
	var json = jsonstr.toJson();
	var valuestr=obj.val();
	//alert(valuestr);
	

	if(valuestr.length>0 & 1==11)
	{
		valuestr=valuestr.replace(/{/g,"{\"");
		valuestr=valuestr.replace(/:/g,"\":\"");
		valuestr=valuestr.replace(/,/g,"\",\"");
		valuestr=valuestr.replace(/}/g,"\"}");
		valuestr=valuestr.replace(/}\",\"{/g,"},{");
		valuestr=valuestr.replace(/\"\"/g,"\"");
	}
	if(valuestr.length==0)
	{
		valuestr="[]";
	}	
	//alert(valuestr);
	var values=valuestr.toJson();
	
	var width= 180;
	var html='<table id="JsonTable" class="eDataTable" border="0" cellpadding="0" cellspacing="0" width="' + ((json.length*(width-10)) + 35 + 35) +  '" style="margin:10px;">';	
	html+='<colgroup>';
	html+='<col width="35" />';
	html+='<col width="' + 120 + '" />';
	html+='<col width="' + 100 + '" />';
	html+='<col width="' + 290 + '" />';
	//for(var i=0;i<json.length;i++)
	//{
		//html+='<col width="' + (width-10) + '" />';
	//}
	html+='<col width="35" />';
	html+='</colgroup>';	
	html+='<thead>';
	html+='<tr>';
	html+='<td height="30" align="center"><img src="../images/add.png" style="cursor:pointer;" onclick="cond_add(\'' + objid + '\');" /></td>';
	json.foreach(function (e)
    {
		html+='<td height="30">' + json[e].text + '</td>';
	});
	html+='<td>顺序</td>';
	html+='</tr>';
	html+='</thead>';
	html+='<tbody eMove="true">';

	for(var j=0;j<values.length;j++)
	{

		html+='<tr>';
		html+='<td height="30" align="center"><img src="../images/del.png" style="cursor:pointer;" onclick="cond_del(this);" /></td>';
		json.foreach(function (e)
		{
			if(json[e].value.toLowerCase()=="code") //code
			{
				html+='<td><select name="' + json[e].value + '" style="height:24px;">';
				$.each(ColumnsJson, function()
				{
				   	html+='<option value="' + this["value"] + '"'+(values[j][json[e].value].toLowerCase() == this["value"].toLowerCase() ? " selected" : "")+'>' + this["text"] + '</option>';
				});

				html+='</select></td>';
			}
			else if(json[e].value.toLowerCase()=="operator") //operator
			{
				html+='<td><select name="' + json[e].value + '" style="height:24px;">';				
				html+='<option value="like"'+(values[j][json[e].value].toLowerCase() == "like" ? " selected" : "")+'>包含</option>';
				html+='<option value="="'+(values[j][json[e].value].toLowerCase() == "=" ? " selected" : "")+'>等于</option>';
				html+='<option value=">"'+(values[j][json[e].value].toLowerCase() == ">" ? " selected" : "")+'>大于</option>';
				html+='<option value="<"'+(values[j][json[e].value].toLowerCase() == "<" ? " selected" : "")+'>小于</option>';
				html+='<option value="<>"'+(values[j][json[e].value].toLowerCase() == "<>" ? " selected" : "")+'>不等于</option>';
				html+='</select></td>';
			}
			else// value
			{
				//alert(values[j][json[e].value])
				html+='<td>';
				html+='<select onchange="cond_change(this);" style="height:24px;">';
				html+='<option value=""'+(values[j][json[e].value] == "输入值" ? " selected" : "")+'>输入值</option>';
				html+='<option value="{site:ColumnID(栏目ID)}"'+(values[j][json[e].value] == "{site:ColumnID(栏目ID)}" ? " selected" : "")+'>栏目ID</option>';
				html+='<option value="{site:ParentColumnID(上级栏目ID)}"'+(values[j][json[e].value] == "{site:ParentColumnID(上级栏目ID)}" ? " selected" : "")+'>上级栏目ID</option>';
				html+='<option value="{site:TopColumnID(顶级栏目ID)}"'+(values[j][json[e].value] == "{site:TopColumnID(上级栏目ID)}" ? " selected" : "")+'>顶级栏目ID</option>';
				html+='<option value="{data:ID(数据ID)}"'+(values[j][json[e].value] == "{data:ID(数据ID)}" ? " selected" : "")+'>数据ID</option>';
				html+='<option value="{site:WebCode(网站ID)}"'+(values[j][json[e].value] == "{site:WebCode(网站ID)}" ? " selected" : "")+'>网站ID</option>';
				html+='<option value="NULL"'+(values[j][json[e].value].toLowerCase() == "null" ? " selected" : "")+'>NULL</option>';
				html+='</select>';				
				html+='<input type="text" name="' + json[e].value + '" value="' + values[j][json[e].value] + '" style="border:1px solid #ccc;padding:3px 5px 3px 5px;background-color:transparent;width:50%;" />';
				html+='</td>';
			}
			

		});
		html+='<td style="cursor:move;">' + (j+1) + '</td>';
		html+='</tr>';

	}

	html+='</tbody>';
	html+='</table>';
	

	
	
	layer.open({
      type: 1,
	  title: "设置条件",
	  scrollbar: false,
      area: [(json.length*width + 20 + 35 + 35 + 20) + 'px', '35%'],
      shadeClose: true, //点击遮罩关闭
	  content: html,
	  btn: ['确定', '取消'],
	  yes: function(index,layero)
	  {

		  var hasnull=false;
		  var _json='[';
		  var _html='';
		  var _cond='';
		 $("#JsonTable tbody tr").each(function(index1,obj){
			if(index1>0)
			{
				_json+=',';
				_cond+=' and ';
			}
			_json+='{';
			$(obj).find("select,input").each(function(index2,input){
				if(input.name.length==0){return true;}
				if(input.value.length==0 && input.tagName=="INPUT"){hasnull=true;}
				if(index2>0){_json+=',';} 
				//if(input.name=="text"){_html += '<span style="display:inline-block;margin-right:6px;border:1px solid #ccc;padding:3px 12px 3px 12px;">' + input.value + '</span>';}
				
				_json += '"' + input.name +  '":"' + input.value.replace(/'/g,"").replace(/"/g,"") + '"';
				
			});	
			_json+='}';
			_html+= '<span style="display:inline-block;margin-right:10px;border:1px solid #ccc;padding:2px 12px 2px 12px;">';
			//_html+= $(obj).find("select:eq(0)").find("option:selected").text() + ' ' + $(obj).find("select:eq(1)").find("option:selected").text() + " \"" +   $(obj).find("input:eq(0)").val().replace(/'/g,"").replace(/"/g,"") + "\"";
			
			var _info= $(obj).find("input:eq(0)").val().replace(/'/g,"").replace(/"/g,"");
			_info = _info.replace(/{(.*?):(.*?)\((.*?)\)}/g,"$3");
			
			_html+= $(obj).find("select:eq(0)").find("option:selected").text() + ' ' + $(obj).find("select:eq(1)").find("option:selected").text() + " \"" +   _info + "\"";
			
			_html+='</span>';
			_cond+= $(obj).find("select:eq(0)").val() + " " + $(obj).find("select:eq(1)").val();
			if( $(obj).find("select:eq(1)").val()=="like")
			{
				_cond+=" '%" + $(obj).find("input:eq(0)").val().replace(/'/g,"").replace(/"/g,"") + "%'";
			}
			else
			{
				_cond+=" '" + $(obj).find("input:eq(0)").val().replace(/'/g,"").replace(/"/g,"") + "'";
			}
			_cond=_cond.replace(/ = 'NULL'/g," is Null");
		});
		if(hasnull){alert("数据不能为空!");return;}
		_json+=']';
		if(_json.length==0){_json='';}
		obj.val(_json);	
		
		$("#fc").val(_cond);
		
		
		$("#spancond").html(_html);
		layer.close(index);
	  },
      cancel: function (index, layero) 
	  {
	  	//arrLayerIndex.pop();
      },
	  success: function (layero, index)
	  {
	  	//arrLayerIndex.push(index);

		var tb=getobj("JsonTable");
		if(tb)
		{
			tb=new eDataTable("JsonTable",1);
			tb.moveRow=function(index,nindex)
			{
				$("#JsonTable tbody > tr > td:last-child").each(function(index1,obj){
					$(obj).html(1+index1);
				}); 
			};		
		}

      }
    });
	
};
function getFields(mid)
{
	
	if(mid.length>10)
	{
		/*
		var text=$("#info").html();
		var reg = new RegExp("[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}","gi"),r;		
		if (r=text.match(reg))
		{
			text=text.replace(r[0],mid); 
		}
		$("#info").html(text);
		*/
	}
	var url="?";	
	if(typeof(AppItem)=="string" && AppItem.length > 0){url+="AppItem=" + AppItem;}
	if(typeof(ModelID)=="string" && ModelID.length > 0){url+="ModelID=" + ModelID;}	
	url+="&act=gettable&mid=" + mid + "&t=" + now();		
	$.ajax({
			type: "get",
			url: url,			
			dataType: "html",
			success: function(html)
			{
				$("#spanfields").html(html);
			}
	});
};
/*网站管理-结束*/

//eColumnMenu.js
var sUserAgent = navigator.userAgent.toLowerCase();
var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
var bIsMidp = sUserAgent.match(/midp/i) == "midp";
var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
var bIsAndroid = sUserAgent.match(/android/i) == "android";
var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
var bisMobile=(bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM);



function showColumnMenu(obj)
{		

	var box=document.getElementById("column_menu");	

	if(!box){return;}	
	if(typeof(sortmenu_close)=="function")
	{
		sortmenu_close();
	}
	//if (!$(box).is(":hidden"))
	if(box.style.display.length==0)
	{
		//var evt=getEvent();
		//if (evt.stopPropagation){evt.stopPropagation();}else{event.cancelBubble = true;}
		//if (evt.preventDefault){evt.preventDefault();}else{evt.cancelBubble = true;}
		cancelColumnMenu();
		return;
	}
	var Rect = obj.getBoundingClientRect();
	box.style.left="-2000px";
	box.style.top="-2000px";
	showObject(box);
	
	//box.style.left=(new eScroll().left +　Rect.right - box.offsetWidth) + "px";
	//box.style.top=(new eScroll().top +　Rect.bottom - 1) + "px";
	$(box).css("left",($(obj).position().left - box.offsetWidth + obj.offsetWidth) + "px");	
	$(box).css("top",($(obj).position().top + obj.offsetHeight) + "px");	

	
	if (window.addEventListener)
	{
		/*
		if(bisMobile)
		{
			document.addEventListener("touchstart",cancelColumnMenu, false);
		}
		else
		{
			document.addEventListener("mouseup",cancelColumnMenu, false);
			document.addEventListener("keyup",ColumnMenu_Esc, true);
		}
		*/
		document.addEventListener("mouseup",cancelColumnMenu, false);
		document.addEventListener("keyup",ColumnMenu_Esc, true);
	}
	else
	{
		document.attachEvent("onmouseup",cancelColumnMenu);
		document.attachEvent("onkeyup",ColumnMenu_Esc);
	}
	//if(document.ontouchstart){alert(3); }
	//if(document.touchstart){alert(43); }
};
function getEvent()
{
	var evt;
	if(window.event)
	{
		evt=window.event;
	}
	else
	{
		var o = arguments.callee;
		var e;
		while(o != null)
		{
			e = o.arguments[0];
			if(e && (e.constructor == Event || e.constructor == MouseEvent))
			{
				evt=e;
				break;
			}
			o = o.caller;
		}
	}
	return evt;
};
function ColumnMenu_Esc()
{
	var event = arguments[0]||window.event; 
	var keyCode=event.which || event.keyCode;
	if(keyCode==27){cancelColumnMenu();}
};
function cancelColumnMenu()
{

	var evt=getEvent();
	if(evt.button==2){return;}	
	var src= evt.srcElement || evt.target;
		if(src.tagName=="INPUT" || src.tagName=="LABEL" || src.tagName=="SPAN" || src.tagName=="A")
		{
			return;
		}
	//document.title=src.tagName;
	//return;
	hideObject("column_menu");
	if (document.addEventListener)
	{
		/*
		if(bisMobile)
		{
			document.removeEventListener('touchstart', cancelColumnMenu, false);
		}
		else
		{
			document.removeEventListener('mouseup', cancelColumnMenu, false);
			document.removeEventListener('keyup', ColumnMenu_Esc, true);
		}
		*/
		document.removeEventListener('mouseup', cancelColumnMenu, false);
		document.removeEventListener('keyup', ColumnMenu_Esc, true);
	}
	else
	{
		document.detachEvent("onmouseup",cancelColumnMenu);
		document.detachEvent("onkeyup",ColumnMenu_Esc);
	}
	
	//alert(document.ontouchstart);
	//alert(3);
};
function saveColumn(obj)
{
	var div=$(obj).parents("div:first");
	var inputs=div.find("input:checked");
	if(inputs.length==0)
	{
		alert("不能全部取消!");
		return;
	}	
	inputs=div.find("input");
	var columns="";
	inputs.each(function(i,el){
		if(i>0)columns+=";";
		columns += $(this).val() + "," + (el.checked?1:0);		
	});
	//alert(columns);
	var url="?";
	if(typeof(AppItem)=="string" && AppItem.length > 0){url+="AppItem=" + AppItem;}
	if(typeof(ModelID)=="string" && ModelID.length > 0){url+="ModelID=" + ModelID;}	
	url+="&act=showallcolumn&t=" + now();
	$.ajax({
		   type: "POST",
			data:{columns:columns},
			url: url,
			dataType: "html",
			success: function(data)
			{
				//cancelColumnMenu();
				// Search();
				document.location.assign(document.location.href.replace("#",""));
			}
	});
};
function showColumn(obj,ajax)
{
	var value=0;
	var ct=$(obj).parent().find(".cur").length;	
	if(ct==1 && obj.className=="cur")
	{
		alert("不能全部取消!");
		return;
	}
	if(obj.className=="cur")
	{
		obj.className="";		
	}
	else
	{
		obj.className="cur";
		value=1;
	}
	hideObject("column_menu");
	var modelitemid=obj.getAttribute("CellID");
	var url="?";	
	if(typeof(AppItem)=="string" && AppItem.length > 0){url+="AppItem=" + AppItem;}
	if(typeof(ModelID)=="string" && ModelID.length > 0){url+="ModelID=" + ModelID;}	
	url+="&act=showcolumn&modelitemid=" + modelitemid + "&value=" + value + "&t=" + now();
	//$.ajax({type:"GET",async:false,url:_url,dataType:"html"});	
	if(ajax)
	{ 
		//document.title=ajax;
		$.ajax({
			   type:"GET",
			   async:false,
			   url:url,
			   dataType:"html",
			   success:function(data)
			   {
				   //var page=$("#page").val();
				   //Search(page);
				   Search();
			   }
		});	
	}
	else
	{
		$.ajax({type:"GET",async:false,url:url,dataType:"html",success:function(data)
			{
				document.location.assign(document.location.href.replace("#",""));
			}
		});
		
	}
};
//selInput.js
function set_selText(obj)
{
	var span=obj.parentNode.parentNode;
	var input =span.getElementsByTagName("input")[0];
	input.value=obj.innerHTML;
	
	var ul = obj.parentNode;	
	ul.style.display="none";
	ul.parentNode.style.zIndex=1;
	
	if(event.cancelBubble){event.cancelBubble=true;event.returnValue=false;}
	else{event.stopPropagation();event.preventDefault();}
};
var seltextul=null;
function show_selText(obj)
{
	var src = getsrcElement(); 
	var ul =obj.getElementsByTagName("ul")[0];
	if(src.tagName == "INPUT" && ul.style.display != "none"){obj.style.zIndex=1;ul.style.display="none";return;}	
	if(src.tagName != "SPAN"){return;}
	
	
	if(event.cancelBubble){event.cancelBubble=true;event.returnValue=false;}
	else{event.stopPropagation();event.preventDefault();}
	
	if(ul.style.display=="none")
	{
		seltextul=ul;
		ul.style.display="";
		obj.style.zIndex=1000;
		//ul.parentNode.style.zIndex=10000+parseInt(ul.parentNode.style.zIndex);
		//alert(obj.className + "::" + obj.style.zIndex);
		if (document.addEventListener){document.addEventListener("click",selText_click, false);}
		else{document.attachEvent("click",selText_click);}
	}
	else
	{
		seltextul=null;
		ul.style.display="none";
		obj.style.zIndex=1;
		if (document.removeEventListener){document.removeEventListener("click", selText_click, false);}
		else{document.detachEvent("click",selText_click);}
	}
};
function selText_click()
{
	if(seltextul)
	{
		seltextul.style.display="none";
		$(seltextul).parent()[0].style.zIndex=1;		
		seltextul=null;		

		if (document.removeEventListener){document.removeEventListener("click", selText_click, false);}
		else{document.detachEvent("click",selText_click);}
	}
};
function getsrcElement()
{
	var evt,src;
	if(window.event)
	{
		evt=window.event;
		src = evt.srcElement;
	}
	else
	{
		var o = arguments.callee;
		var e;
		while(o != null)
		{
			e = o.arguments[0];
			if(e && (e.constructor == Event || e.constructor == MouseEvent))
			{
				evt=e;src=evt.target; 
				break;
			}
			o = o.caller;
		}
	}
	return src;	
};

//eEditer.js
//编码
function HtmlEncode(str)
{
	if(str.length == 0) return "";
	 var s = str.replace(/ /g,"&nbsp;");
	 s = s.replace(/\n/g,"<br>");
     s = s.replace(/\'/g,"&#39;");
     s = s.replace(/\"/g,"&quot;");
     return s;  
};
function eediter_setjson(ul)
{
	var json='[';
	ul.find("li").each(function(index, element){
		if(index>0){json+=',';}
		
		json+='{"type":"' + $(this).attr("data-type") + '","body":"' ;
		
		if( $(this).attr("data-type")=="text")
		{
			json+=HtmlEncode($(this).find("textarea:eq(0)").val());//.encode() ;
			//json+=decodeURIComponent($(this).find("textarea:eq(0)").val());			
		}
		else if($(this).attr("data-type")=="image")
		{
			json+= $(this).find("img:eq(0)").attr("src") ;
		}
		else
		{
			json+= $(this).find("span:eq(0)").attr("src") ;
		}
		
		json+= '"}';
    });
	json+=']';	
	var txtid=ul.parent().attr("id").replace("_body","");
	json=json.replace(/\"/g,"\\u0022");
	ul.parent().find("#" + txtid).val(json);
};

function eediter_del(obj)
{
	var _back=confirm('确认要删除吗？');
	if(!_back){return;};
	var type=$(obj).parent().attr("data-type");
	if(type=="image")
	{
		var img=$(obj).parent().find("img:eq(0)").attr("src");
		if(img.toLowerCase().indexOf("/temp/") > -1)
		{
			var url=$(obj).parent().parent().parent().attr("vpath") + "Plugins/ProUpload.aspx?act=del&file=" + img;
			$.ajax({
				type: "GET", async: true,
				url: url,
				dataType: "html",
				success: function (data) {}
			 });		
		}
	}
	
	var ul=$(obj).parent().parent()
	$(obj).parent().remove();
	eediter_setjson(ul);
};
function eediter_add(type)
{
	var html='<li data-type="text">';
    html+='<textarea onblur="eediter_setjson($(this).parents(\'ul:first\'));"></textarea>';
	html+='<a class="del" href="javascript:;" onclick="eediter_del(this);"></a>';
    html+='</li>';	
	var src = getsrcElement();	
	var ul=$(src).parent().parent().find("ul:eq(0)");
	ul.append(html);
	ul.find("li").arrangeable();
};
function eediter_upload(obj,type)
{
	var url=$(obj).parent().parent().attr("vpath") + "Plugins/ProUpload.aspx?type=file";
	var maxWidth=$(obj).parent().parent().attr("maxWidth");
	if(maxWidth){url+="&MaxWidth=" + maxWidth;}

	if(obj.files)
	{
		var formData = new FormData();
		for(var i=0;i<obj.files.length;i++)
		{
			formData.append('files', obj.files[i], obj.files[i].name);
		}		
		$(obj).hide();
		$.ajax({
            type: "POST", 
			async: true,
			data:formData,
            url: url,           
			contentType: false,
			//dataType: "formData",
			cache: false,//上传文件无需缓存
            processData: false,//用于对data参数进行序列化处理 这里必须false
			dataType: "json",
            success: function (data) 
			{
				//alert(JSON.stringify(data));
				if (data.errcode == "0") 
				{
					for(var i=0;i < data.files.length; i++)
					{
						//alert( data.files[i].url);
						if(type=="image")
						{
							$(obj).parent().parent().find("ul:eq(0)").append('<li data-type="' + type + '"><img src="' + data.files[i].url + '" class="editerimg" ondragstart="return false;" ondrag="return false;" /><a href="javascript:;" class="del" onclick="eediter_del(this);"></a></li>');		
						}
						else
						{
							$(obj).parent().parent().find("ul:eq(0)").append('<li data-type="' + type + '" class="' + type + '"><span src="' + data.files[i].url + '"></span><a href="javascript:;" class="del" onclick="eediter_del(this);"></a></li>');		
						}
					}
				}
				else
				{
					layer.msg(data.message);
				}
				obj.value="";
				$('.eediter li').arrangeable();
				var ul=$(obj).parent().parent().find("ul");
				eediter_setjson(ul);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
				obj.value="";
			}
        });
		$(obj).show();	
	}
	else
	{
		$.ajaxFileUpload ({
		 	type: "post",
			url: url, //用于文件上传的服务器端请求地址 
			secureuri: false, //一般设置为false 
			fileElementId: $(obj).attr("id"), //文件上传空间的id属性  <input type="file" id="file" name="file" /> 
			dataType: "json", //返回值类型 一般设置为json 			
			success: function (data, status)  //服务器成功响应处理函数
			{
				//alert(JSON.stringify(data));
				if (data.errcode == "0") 
				{
					for(var i=0;i < data.files.length; i++)
					{
						//$(obj).parent().parent().find("ul:eq(0)").append('<li data-type="text"><img src="' + data.files[i].url + '" class="editerimg" ondragstart="return false;" ondrag="return false;" /><a href="javascript:;" class="del" onclick="eediter_del(this);"></a></li>');		
						if(type=="image")
						{
							$(obj).parent().parent().find("ul:eq(0)").append('<li data-type="' + type + '"><img src="' + data.files[i].url + '" class="editerimg" ondragstart="return false;" ondrag="return false;" /><a href="javascript:;" class="del" onclick="eediter_del(this);"></a></li>');		
						}
						else
						{
							$(obj).parent().parent().find("ul:eq(0)").append('<li data-type="' + type + '" class="' + type + '"><span src="' + data.files[i].url + '"></span><a href="javascript:;" class="del" onclick="eediter_del(this);"></a></li>');		
						}
					}
				}
				else
				{
					layer.msg(data.message);
				}
				obj.value="";
				var ul=$(obj).parent().parent().find("ul");
				eediter_setjson(ul);
			}, 
			error: function (data, status, e)//服务器响应失败处理函数
			{
			} 
		});	
	}	
};

//移动端
//插入位置
function getAppendAreav1(ul)
{
	var top=document.body.scrollTop;
	var rect=ul.get(0).getBoundingClientRect();
	if(ul.children().length==0)//
	{
		return {obj:ul.get(0),up:true};
	}
	else
	{	
		var editer_tool= $(".mediter_tool:eq(0)");
		var span=editer_tool.find("span:eq(0)");	
		var toolTop = top + editer_tool.get(0).offsetTop + span.get(0).offsetTop;
		var rec=ul.get(0).getBoundingClientRect();

		if((top + rec.top) > toolTop) //最顶部
		{
			return {obj:ul.get(0),up:true};
		}
		else if(toolTop > (top + rec.top + ul.get(0).offsetHeight))//最底部
		{
			return {obj:ul.get(0),up:false};
		}
		else
		{
			for(var i=0;i<ul.children().length;i++)
			{
				var rect=ul.children()[i].getBoundingClientRect();
				var _min= top +  rect.top; 
				var _max=_min + ul.children()[i].offsetHeight;
				if(_min < toolTop && _max > toolTop)
				{
					if(toolTop < (_min +  parseInt(ul.children()[i].offsetHeight/2)))
					{
						return {obj:ul.children()[i],up:true};
					}
					else
					{
						return {obj:ul.children()[i],up:false};
					}
				}
			}			
		}
	}	
};
function getAppendArea(ul)
{
	var top=ul.get(0).parentNode.scrollTop;
	if(ul.children().length==0)//
	{
		return {obj:ul.get(0),up:true};
	}
	else
	{		
		if(parseInt(ul.children()[0].offsetHeight/2) > top) //最顶部
		{
			return {obj:ul.get(0),up:true};
		}
		else if(top >= ul.get(0).offsetHeight)//最底部
		{
			return {obj:ul.get(0),up:false};
		}
		else
		{
			for(var i=0;i<ul.children().length;i++)
			{		
				var _min= parseInt(ul.children()[i].offsetTop) + 14; 
				var _max=_min +  parseInt(ul.children()[i].offsetHeight);
				if(_min < top && _max > top)
				{
					if(top < (_min +  parseInt(ul.children()[i].offsetHeight/2)))
					{
						return {obj:ul.children()[i],up:true};
					}//
					else
					{
						return {obj:ul.children()[i],up:false};
					}
				}
			}			
		}
	}	
};
//添加节点
function mediter_add(obj,type,value)
{
	var html='<li data-type="'+ type +'">';
    html+='<dl>';
    html+='<dt>';
	html+='<a href="javascript:;" onclick="mediter_del(this);" class="titledel">&nbsp;</a>';
    html+='<a href="javascript:;" onclick="mediter_move(this,false);" class="titledown">&nbsp;</a>';
    html+='<a href="javascript:;" onclick="mediter_move(this,true);" class="titleup">&nbsp;</a>';
    html+='</dt>';
    html+='<dd>';
	switch(type)
	{
		case "title":
			html+='<input onblur="mediter_setjson($(this).parents(\'ul:first\'));" placeholder="请输入标题" />';
			break;
		case "text":
			html+='<textarea onblur="mediter_setjson($(this).parents(\'ul:first\'));" placeholder="请输入内容" />';
			break;
		case "image":
			html+='<img src="' + value + '" />';
			break;
		case "audio":
			html+='<audio src="' + value + '" controls="controls" />';
			break;
		case "video":
			html+='<video src="' + value + '" controls="controls" />';
			break;
	}
	html+='</dd>';
    html+='</dl>';
    html+='</li>';
	var ul=$(obj).parents(".mediter").find("ul:eq(0)");
	var area=getAppendArea(ul);
	if(area.obj.tagName=="UL")
	{
		if(area.up)
		{
			$(area.obj).prepend(html);//最前面
		}
		else
		{
			$(area.obj).append(html);//底部
		}
	}
	else
	{
		if(area.up)
		{
			$(area.obj).before(html);//前
		}
		else
		{
			$(area.obj).after(html);//后
		}
	}
	
};
//删除内容
function mediter_del(obj)
{
	var _back=confirm('确认要删除吗？');
	if(!_back){return;};
	var tmp="";
	var li=$(obj).parents("li:first");	
	var type=li.attr("data-type");
	var ul=li.parent();
	switch(type)
	{
		case "text":
			break;
		case "image":
			tmp=li.find("dd img").attr("src");
			break;
		case "audio":
			tmp=li.find("dd audio").attr("src");
			break;
		case "video":
			tmp=li.find("dd video").attr("src");
			break;
	}
	if(tmp.toLowerCase().indexOf("/temp/") > -1)
	{
		var url= li.parents(".mediter").attr("vpath") + "Plugins/ProUpload.aspx?act=del&file=" + tmp;
		$.ajax({
			type: "GET", async: true,
			url: url,
			dataType: "html",
			success: function (data) {}
		});		
	}	
	li.remove();	
	mediter_setjson(ul);
};
//移动内容
function mediter_move(obj,up)
{
	var li=$(obj).parents("li:first");
	var ul=li.parent();
	if(up)
	{
		if(li.index()==0)
		{
			//alert("已经在顶部!");
			layer.msg("已经在顶部!");
			return;
		}
		li.prev().before(li);
	}
	else
	{
		if(li.index()==ul.children().length-1)
		{
			//alert("已经在底部!");
			layer.msg("已经在底部!");
			return;
		}
		li.next().after(li);
	}
	
	var ids="";
	ul.children().each(function(index,elem)
	{
		
		if(index>0){ids+=',';}
		ids+= $(elem).attr("rowid");
    });	
	mediter_setjson(ul);
};
function mediter_setjson(ul)
{
	var json='[';
	ul.find("li").each(function(index, elem)
	{
		if(index>0){json+=',';}
		var type=$(elem).attr("data-type").toLowerCase();
		switch(type)
		{
			case "title":
				json+='{"type":"title","body":"' + HtmlEncode($(elem).find("input").val()) + '"}';
				break;
			case "text":
				json+='{"type":"text","body":"' + HtmlEncode($(elem).find("textarea").val()) + '"}';
				break;
			case "image":
				json+='{"type":"image","body":"' + $(elem).find("img").attr("src") + '"}';
				break;
			case "audio":
				json+='{"type":"audio","body":"' + $(elem).find("audio").attr("src") + '"}';
				break;
			case "video":
				json+='{"type":"video","body":"' + $(elem).find("video").attr("src") + '"}';
				break;
		}
    });	
	json+=']';	
	var txtid=ul.parents(".mediter").attr("id").replace("_body","");	
	$("#"+ txtid).val(json);
};
function mediter_upload(obj,type)
{
	var div=$(obj).parents(".mediter");
	var url=div.attr("vpath") + "Plugins/ProUpload.aspx?type=file";
	var maxWidth=div.attr("maxWidth");
	if(maxWidth){url+="&MaxWidth=" + maxWidth;}
	if(obj.files)
	{
		var formData = new FormData();
		for(var i=0;i<obj.files.length;i++)
		{
			formData.append('files', obj.files[i], obj.files[i].name);
		}		
		$(obj).hide();
		$.ajax({
            type: "POST", 
			async: true,
			data:formData,
            url: url,           
			contentType: false,
			//dataType: "formData",
			cache: false,//上传文件无需缓存
            processData: false,//用于对data参数进行序列化处理 这里必须false
			dataType: "json",
            success: function (data) 
			{
				if (data.errcode == "0") 
				{
					for(var i=0;i < data.files.length; i++)
					{						
						mediter_add($(obj).parent().get(0),type,data.files[i].url);
					}
				}
				else
				{
					layer.msg(data.message);
				}
				obj.value="";
				//var ul=$(obj).parent().parent().next();
				var ul=$(obj).parents(".mediter").find("ul:eq(0)");
				mediter_setjson(ul);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
			}
        });
		
		$(obj).show();
	}
	else
	{
		$(obj).hide();
		$.ajaxFileUpload ({
		 	type: "post",
			url: url, //用于文件上传的服务器端请求地址 
			secureuri: false, //一般设置为false 
			fileElementId: $(obj).attr("id"), //文件上传空间的id属性  <input type="file" id="file" name="file" /> 
			dataType: "json", //返回值类型 一般设置为json 			
			success: function (data, status)  //服务器成功响应处理函数
			{
				if (data.errcode == "0") 
				{
					for(var i=0;i < data.files.length; i++)
					{
						mediter_add(type,data.files[i].url);
					}
				}
				else
				{
					layer.msg(data.message);
				}
				obj.value="";
				//var ul=$(obj).parent().parent().next();
				var ul=$(obj).parents(".mediter").find("ul:eq(0)");
				mediter_setjson(ul);
			}, 
			error: function (data, status, e)//服务器响应失败处理函数
			{
			} 
		});	
		$(obj).show();
	}
};

//eFileList.js
function eFileList_setjson(ol)
{
	var json='[';
	ol.find("li").each(function(index, element){		
		if(index>0){json+=',';}
		json+='{"name":"' + $(this).find("a:eq(0)").text() + '","url":"' + $(this).find("a:eq(0)").attr("href") + '"}';
    });
	json+=']';
	var txtid=ol.parent().attr("id").replace("_body","");
	ol.parent().find("#" + txtid).val(json);
	/*
	if(json.length>2)
	{
		ol.parent().find("[type='hidden']").val(json);
	}
	else
	{
		ol.parent().find("[type='hidden']").val("");
	}
	*/
};
function eFileList_del(obj)
{
	if(!confirm("确认要删除吗？")){return;}
	var ol=$(obj).parent().parent();
	var src=$(obj).parent().find("a:eq(0)").attr("href");
	if(src.toLowerCase().indexOf("/temp/") > -1)
	{
		var url=ol.parent().attr("vpath") + "Plugins/ProUpload.aspx?act=del&file=" + src;
		$.ajax({
		   	type: "GET", async: true,
           	url: url,
           	dataType: "html",
           	success: function (data) {}
      	 });		
	}
	$(obj).parent().remove();
	eFileList_setjson(ol);	
};
function eFileList_upload(obj)
{	
	var url=$(obj).parent().parent().attr("vpath") + "Plugins/ProUpload.aspx?type=file";
	var maxWidth=$(obj).parent().parent().attr("maxWidth");
	if(maxWidth){url+="&MaxWidth=" + maxWidth;}
	if(obj.files)
	{
		var formData = new FormData();
		for(var i=0;i<obj.files.length;i++)
		{
			formData.append('files', obj.files[i], obj.files[i].name);
		}		
		$(obj).hide();
		$.ajax({
            type: "POST", 
			async: true,
			data:formData,
            url: url,           
			contentType: false,
			//dataType: "formData",
			cache: false,//上传文件无需缓存
            processData: false,//用于对data参数进行序列化处理 这里必须false
			dataType: "json",
            success: function (data) 
			{
				//alert(JSON.stringify(data));
				if (data.errcode == "0") 
				{
					for(var i=0;i < data.files.length; i++)
					{		
						$(obj).parent().parent().find("ol:eq(0)").append('<li><a href="' + data.files[i].url + '" target="_blank">' + data.files[i].name + '</a><a href="javascript:;" class="del" onclick="eFileList_del(this);">&nbsp;</a></li>');					
					}
				}
				else
				{
					layer.msg(data.message);
				}
				var ol=$(obj).parent().parent().find("ol");			
				obj.value="";
				eFileList_setjson(ol);				
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
			}
        });
		$(obj).show();	
	}
	else
	{
		 $.ajaxFileUpload ({
		 	type: "post",
			url: url, //用于文件上传的服务器端请求地址 
			secureuri: false, //一般设置为false 
			fileElementId: $(obj).attr("id"), //文件上传空间的id属性  <input type="file" id="file" name="file" /> 
			dataType: "json", //返回值类型 一般设置为json 			
			success: function (data, status)  //服务器成功响应处理函数
			{
				//alert(JSON.stringify(data));
				if (data.errcode == "0") 
				{
					for(var i=0;i < data.files.length; i++)
					{
						$(obj).parent().parent().find("ol:eq(0)").append('<li><a href="' + data.files[i].url + '" target="_blank">' + data.files[i].name + '</a><a href="javascript:;" class="del" onclick="eFileList_del(this);">&nbsp;</a></li>');			
					}
				}
				else
				{
					layer.msg(data.message);
				}
				var ol=$(obj).parent().parent().find("ol");
				obj.value="";
				eFileList_setjson(ol);
			}, 
			error: function (data, status, e)//服务器响应失败处理函数
			{
			} 
		});		 
	}
};

//eReport.js
  function now() { date = new Date(); var t = date.getFullYear().toString(); t += (date.getMonth() + 1).toString(); t += (date.getDate()).toString(); t += (date.getHours()).toString(); t += (date.getMinutes()).toString(); t += (date.getSeconds()).toString(); t += (date.getMilliseconds()).toString(); return t; };

    function close_eDlg() {
        //$(".eDlg").hide();
        //$(".eDlg").css("top", "-2000px");
        //$(".eDlg").css("left", "-2000px");
        $(".eDlg").remove();
    };
    function eReport_Refresh(ReportID, CtrlID, ObjID, timeObj)
    {
        if (timeObj) { clearInterval(timeObj); }
        var rep = $("#" + CtrlID).parent();
        var timetype = rep.attr("TimeType") ? rep.attr("TimeType") : "";
        var ctrltype = rep.attr("ControlType");
        var url = "?ctrltype=" + ctrltype + "&ReportID=" + ReportID;
		
		
		if(typeof(AppItem)=="string" && AppItem.length > 0)
		{
			url+="&AppItem=" + AppItem;
		}
		else
		{
			if(typeof(ModelID)=="string" && ModelID.length > 0){url+="&ModelID=" + ModelID;}
		}
		
        if (ObjID.length > 0) { url += "&obj=" + ObjID; }
        if (timetype.length > 0)
        {
            if (timetype == "year")
            {
                url += "&syear=" + rep.attr("SYear") + "&eyear=" + rep.attr("EYear");
            }
            if (timetype == "quarter" || timetype == "month") {
                url += "&year=" + rep.attr("DefaultYear");
            }
            if (timetype == "day") {
                url += "&year=" + rep.attr("DefaultYear") + "&month=" + rep.attr("DefaultMonth");
            }            
        }
        url += "&t=" + now();
        $.ajax({
            type: 'get',
            url: url,
            dataType: "html",
            success: function (data) {
                rep.html(data);

            }
        });

    };
    function eReport_Confirm(ReportID, CtrlID, ObjID, timeObj)
    {      
        
        var rep = $("#" + CtrlID).parent();
        var timetype = rep.attr("TimeType");
        var ctrltype = rep.attr("ControlType");
        var maxyear = 0;
        var minyear = 0;
        if (rep.attr("maxYear").length > 0) maxyear = parseInt(rep.attr("maxYear"));
        if (rep.attr("minYear").length > 0) minyear = parseInt(rep.attr("minYear"));
        var year = 0;
        if (rep.attr("DefaultYear").length > 0) year = parseInt(rep.attr("DefaultYear"));
        var month = 0;
        if (rep.attr("DefaultMonth").length > 0) month = parseInt(rep.attr("DefaultMonth"));

        if ((timetype == "quarter" || timetype == "month") && year == parseInt($(".ereport_year").val()))
        {

            close_eDlg();
            return;
        }

        var url = "?ctrltype=" + ctrltype + "&";
        if (ObjID.length > 0) { url += "obj=" + ObjID + "&"; }
        if (timetype == "year")
        {
            rep.attr("sYear", $(".ereport_syear").val());
            rep.attr("eYear", $(".ereport_eyear").val());
            url += "ReportID=" + ReportID + "&syear=" + $(".ereport_syear").val() + "&eyear=" + $(".ereport_eyear").val();
        }
        if (timetype == "quarter" || timetype == "month")
        {
            rep.attr("DefaultYear", $(".ereport_year").val());
            url += "ReportID=" + ReportID + "&year=" + $(".ereport_year").val();
        }
        if (timetype == "day")
        {
            rep.attr("DefaultYear", $(".ereport_year").val());
            rep.attr("DefaultMonth", $(".ereport_month").val());
            url += "ReportID=" + ReportID + "&year=" + $(".ereport_year").val() + "&month=" + $(".ereport_month").val();
        }
		
		if(typeof(AppItem)=="string" && AppItem.length > 0)
		{
			url+="&AppItem=" + AppItem;
		}
		else
		{
			if(typeof(ModelID)=="string" && ModelID.length > 0){url+="&ModelID=" + ModelID;}
		}
		
		
        url += "&t=" + now();
        if (timeObj) { clearInterval(timeObj); }
        var html = '<div id="eReportLoading" class="loading">&nbsp;</div>';
        rep.append(html);

        $.ajax({
            type: 'get',
            url: url,
            dataType: "html",
            success: function (data) {
                 rep.html(data);
                close_eDlg();
            }
        });

    };
    function eReport_Reset(obj, ReportID, CtrlID, ObjID, timeObj) {
        var rect = obj.getBoundingClientRect();
        var html = '<div class="eDlg">';
        html += '<h1>报表选项<a href="javascript:;" onclick="close_eDlg();"></a></h1>';
        html += '<p></p>';
        html += '<div class="footer"><a class="btn" href="javascript:;" onclick="eReport_Confirm(\'' + ReportID + '\',\'' + CtrlID + '\',\'' + ObjID + '\',' + timeObj + ');">确定</a></div>';
        html += '</div>';
        $(document.body).append(html);


        $(".eDlg").css("top", eScroll().top + rect.top + (rect.bottom - rect.top));
        $(".eDlg").css("left", eScroll().left + rect.left - 200);
        // return;

        var rep = $(obj).parent().parent();

        var timetype = rep.attr("TimeType");
        var ctrltype = rep.attr("ControlType");
        var maxyear = 0;
        var minyear = 0;
        if (rep.attr("maxYear").length > 0) maxyear = parseInt(rep.attr("maxYear"));
        if (rep.attr("minYear").length > 0) minyear = parseInt(rep.attr("minYear"));
        var year = 0;
        if (rep.attr("DefaultYear").length > 0) year = parseInt(rep.attr("DefaultYear"));
        var month = 0;
        if (rep.attr("DefaultMonth").length > 0) month = parseInt(rep.attr("DefaultMonth"));


        html = '<div style="margin:10px;">';
        if (timetype == "year") {
            var syear = 0;
            if (rep.attr("sYear").length > 0) syear = parseInt(rep.attr("sYear"));
            var eyear = 0;
            if (rep.attr("eYear").length > 0) eyear = parseInt(rep.attr("eYear"));

            html += '<select name="select" class="ereport_syear">';
            for (var i = minyear; i <= maxyear; i++) {
                html += '<option value="' + i + '"' + (i == syear ? ' selected="true"' : '') + '>' + i + '年</option>';
            }
            html += '</select>';
            html += ' 至 ';
            html += '<select name="select" class="ereport_eyear">';
            for (var i = minyear; i <= maxyear; i++) {
                html += '<option value="' + i + '"' + (i == eyear ? ' selected="true"' : '') + '>' + i + '年</option>';
            }
            html += '</select>';

        }
        if (timetype == "quarter" || timetype == "month") {
            html += '<select name="select" class="ereport_year">';
            for (var i = minyear; i <= maxyear; i++) {
                html += '<option value="' + i + '"' + (i == year ? ' selected="true"' : '') + '>' + i + '年</option>';
            }
            html += '</select>';
        }
        if (timetype == "day") {

            html += '<select name="select" class="ereport_year">';
            for (var i = minyear; i <= maxyear; i++) {
                html += '<option value="' + i + '"' + (i == year ? ' selected="true"' : '') + '>' + i + '年</option>';
            }
            html += '</select>';

            html += '<select name="select" class="ereport_month">';
            for (var i = 1; i <= 13; i++) {
                html += '<option value="' + i + '"' + (i == month ? ' selected="true"' : '') + '>' + i + '月</option>';
            }
            html += '</select>';
        }
        html += '</div>';
        $(".eDlg p").html(html);
        /*
    layer.open({
    type: 1
	, area: ['200px', '150px']
    //,shade: 0.2 //透明度
  	, title: "报表选项"
	, closeBtn: 1
    , offset: [ (eScroll().top + rect.top) + 'px',( eScroll().left + rect.left - 200) + 'px']
	, scrollbar: false
	, shadeClose: true //开启遮罩关闭
  	, content: html
    , shade: 0
	, btn: ['确定'] //只是为了演示
	, end: function () { }
	, success: function (layero, index) {}
    , yes: function (index) {
        
    }
    });
        */

    };
//fileManage.js
function checkfrm(frm)
{
    if (frm.imgFile.value.length == 0)
	{
		alert("请选择要上传的文件!");
		frm.imgFile.focus();
		return false;
	}
	return true;
};
function addTag(id,txt)
{

	//if(typeof(eaceditor)!="undefined")	
	//if(eaceditor)	
	if(typeof(eaceditor)!="undefined")
	{
		var cursorPosition = eaceditor.getCursorPosition();
		eaceditor.session.insert(cursorPosition, txt);
		return;
	}
	//if(ace_f2)	
	if(typeof(ace_f2)!="undefined")
	{
		var cursorPosition = ace_f2.getCursorPosition();
		ace_f2.session.insert(cursorPosition, txt);
		return;
	}
	 
	var obj=document.getElementById(id);
	if(!obj)
	{
		obj=document.getElementsByClassName(id);
		if(obj && obj.length)
		{
			obj=obj[0];
		}
	}
	if (obj.selectionStart !== undefined)
	{
		document.title=1;
		var startPos = obj.selectionStart;
		var endPos = obj.selectionEnd;
        obj.value = obj.value.substring(0, startPos) + txt + obj.value.substring(endPos, obj.value.length);
		obj.focus();
        obj.selectionStart = startPos + txt.length;
        obj.selectionEnd = startPos + txt.length;
		obj.focus();
	}
	else
	{
		if(document.selection) 
		{ 		  
		  	obj.focus();
            var sel = document.selection.createRange();
            sel.text =  txt;
		}
		else
		{
		  	obj.value=[obj.value,txt].join("");
		}
	}	
};
function showHtmlTag()
{
	
	var url = "?" +  (typeof (AppItem) == "string" && AppItem.length > 0 ? "AppItem=" + AppItem : "ModelID=" + ModelID)  + "&act=getjson";
	$.ajax({type:"get",async:false,url:url,dataType:"json",success:function(json)
		{
			if(json.success=="1")
			{
				viewJson=json.viewJson;
				contentJson=json.contentJson;
				siteJson=json.siteJson;
			}
		}
	});
	var html='';
	html+='<div style="padding:4px 0px 4px 10px;border: 0px dashed #ccc;background-color:#f2f2f2;">全局标签：</div>';
	html+='<div style="margin:6px;">';
	$.each(publicJson, function()
	{
		html+='<a href="javascript:;" class="htmltag" onclick="addTag(\'content\',\'{'+ this["type"] +':'+ this["value"] +'(' + this["text"] + ')}\');">' + this["text"] + '</a>';
	});	
	html+='</div>';
	
	html+='<div style="padding:4px 0px 4px 10px;border: 0px dashed #ccc;background-color:#f2f2f2;">站点标签：</div>';
	html+='<div style="margin:6px;">';
	$.each(siteJson, function()
	{
		html+='<a href="javascript:;" class="htmltag" onclick="addTag(\'content\',\'{site:'+ this["value"] +'(' + this["text"] + ')}\');">' + this["text"] + '</a>';
	});	
	html+='</div>';
	
	html+='<div style="padding:4px 0px 4px 10px;border: 0px dashed #ccc;background-color:#f2f2f2;">动态数据：</div>';
	html+='<div style="margin:6px;">';	
	$.each(viewJson, function()
	{
		html+='<a href="javascript:;" class="htmltag" onclick="addTag(\'content\',\'{view:'+ this["value"] +'(' + this["text"] + ')}\');">' + this["text"] + '</a>';
	});		
	html+='</div>';
	html+='<div style="padding:4px 0px 4px 10px;border: 0px dashed #ccc;background-color:#f2f2f2;">静态数据：</div>';
	html+='<div style="margin:6px;">';
	$.each(contentJson, function()
	{
		html+='<a href="javascript:;" class="htmltag" onclick="addTag(\'content\',\'{content:'+ this["value"] +'(' + this["text"] + ')}\');">' + this["text"] + '</a>';
	});	
	html+='</div>';
	
	layer.open({
					type: 1 //此处以iframe举例
					,title: "插入数据"
					//,skin: 'layui-layer-molv' //加上边框 layui-layer-rim  layui-layer-lan layui-layer-molv layer-ext-moon
					,shadeClose: false //点击遮罩关闭层
					, area: ['80%', '80%']
					,shadeClose: true //点击遮罩关闭
					,shade: 0.2 //透明度
					,maxmin: false
					,resize: false
					,btnAlign: 'l' //lcr
					,moveType: 0 //拖拽模式，0或者1
					,anim: 0 //0-6的动画形式，-1不开启
					,content: html
					,btn: ['返回'] //只是为了演示
					,yes: function(index,layero)
					{ 
						layer.close(index); 
					}	
					,cancel: function(index, layero)
					{
						//layer.msg("X关闭!");
					}
					,success: function(layero, index)
					{
					}
				});
};
function addPath(txt)
{
	var obj=document.getElementById("content");	
	if(!obj)
	{
		var objs=document.getElementsByClassName("ace_text-input");
		if(objs.length>0)
		{
			obj=objs[0];
		}
	}
	if(eaceditor)
	{
		var cursorPosition = eaceditor.getCursorPosition();
		eaceditor.session.insert(cursorPosition, txt);
		parent.layer.close( parent.FileSelectFormIndex);
    	parent.FileSelectFormIndex = null;
		return;
	}
	if (obj.selectionStart !== undefined)
	{
		var startPos = obj.selectionStart;
		var endPos = obj.selectionEnd;
        obj.value = obj.value.substring(0, startPos) + txt + obj.value.substring(endPos, obj.value.length);
		obj.focus();
        obj.selectionStart = startPos + txt.length;
        obj.selectionEnd = startPos + txt.length;
	}
	else
	{
		  if(document.selection) 
		  { 		  
		  	 obj.focus();
             var sel = document.selection.createRange();
             sel.text =  txt;
		  }
		  else
		  {
		  	obj.value=[obj.value,txt].join("");
		  }
	}	
	parent.layer.close( parent.FileSelectFormIndex);
    parent.FileSelectFormIndex = null;
};
function showPathSelect()
{
	var url = "../Plugins/FileSelect.aspx";
    parent.layer.open({
      type: 2,
      title: "选择库文件",
      maxmin: false,
      shadeClose: true, //点击遮罩关闭层
      area : ["900px;" , "700px"],	
	  // content: [url,'no'], 
	  content: url,
	  success: function(layero, index)
	  {
	      parent.FileSelectFormIndex = index;
  	  }
    });	
};
//文件编辑
function edit(name)
{
	//var url = "?" + (typeof (AppItem) == "string" && AppItem.length > 0 ? "AppItem=" + AppItem : "ModelID=" + ModelID) + "&act=edit" + (path.length>0 ? "&path=" + path : "") + "&name=" + name;
	var url = "?";
    if (typeof (AppItem) == "string" && AppItem.length > 0) {
        url += "AppItem=" + AppItem + "&";
    }
    else {
        if (typeof (ModelID) == "string" && ModelID.length > 0) {
            url += "ModelID=" + ModelID + "&";
        }
    }
    url += "act=edit" + (path.length>0 ? "&path=" + path : "") + "&name=" + name;
	$.ajax({type:"get",async:false,url:url,dataType:"json",success:function(json)
		{
			if(json.success=="1")
			{
				var html='';
				html+='<textarea id="content" name="content" class="autoNumber" style="width:98%;height:540px;">' + json.value + '</textarea>';
				layer.open({
					type: 1 //此处以iframe举例
					,title: name
					//,skin: 'layui-layer-molv' //加上边框 layui-layer-rim  layui-layer-lan layui-layer-molv layer-ext-moon
					,shadeClose: false //点击遮罩关闭层
					,area: ['90%', '90%']
					,shade: 0.2 //透明度
					,maxmin: false
					,resize: false
					,btnAlign: 'l' //lcr
					,moveType: 0 //拖拽模式，0或者1
					,anim: 0 //0-6的动画形式，-1不开启
					,content: html
					,btn: ['保存修改','关闭'] //只是为了演示
					,yes: function(index,layero)
					{ 
						//var value=$("#content").val().replace(/\r/ig,"").replace(/\n/ig,"0x\\r\\n");	
						var value=$("#content").val().encode();					
						//url =  "?" + (typeof (AppItem) == "string" && AppItem.length > 0 ? "AppItem=" + AppItem : "ModelID=" + ModelID) + "&act=save" + (path.length>0 ? "&path=" + path : "") + "&name=" + name;			
						url = "?";
						if (typeof (AppItem) == "string" && AppItem.length > 0) {
							url += "AppItem=" + AppItem + "&";
						}
						else {
							if (typeof (ModelID) == "string" && ModelID.length > 0) {
								url += "ModelID=" + ModelID + "&";
							}
						}
						url += "act=save" + (path.length>0 ? "&path=" + path : "") + "&name=" + name;			
						$.ajax({
							type: "post", 
							async: true,
							data:{value:value},
							url: url,
							dataType: "json",
							success: function (data) {
								layer.msg(data.message);
								//layer.close(index); 不关闭、继续修改
							},
							error: function (XMLHttpRequest, textStatus, errorThrown) {				
							}
						});
					}	
					,cancel: function(index, layero)
					{
						//layer.msg("X关闭!");
					}
					,success: function(layero, index)
					{
						//alert($('#layui-layer'+ index).height());
						var h=$('#layui-layer'+ index).height()-110;
						var w=$('#layui-layer'+ index).width()-6;
						$("#content").height(h).width(w);
						$("#content").setTextareaCount({width: "40px",bgColor: "#f2f2f2",color: "#000",display: "inline-block"});
					}
				});
			}
		}
	});		
};
//模板编辑
function editFile(name)
{
	//var url = "?" +  (typeof (AppItem) == "string" && AppItem.length > 0 ? "AppItem=" + AppItem : "ModelID=" + ModelID)  + "&act=edit" + (path.length>0 ? "&path=" + path : "") + "&name=" + name;
	var url = "?";
    if (typeof (AppItem) == "string" && AppItem.length > 0) {
        url += "AppItem=" + AppItem + "&";
    }
    else {
        if (typeof (ModelID) == "string" && ModelID.length > 0) {
            url += "ModelID=" + ModelID + "&";
        }
    }
    url += "act=edit" + (path.length>0 ? "&path=" + path : "") + "&name=" + name;
	$.ajax({
		   type:"get",
		   async:false,
		   url:url,
		   dataType:"json",
		   success:function(json)
		{
			if(json.success=="1")
			{
				var html='';
				if(name.toLowerCase().indexOf(".html")>-1)
				{
					html+='<div style="padding:8px;background-color:#f2f2f2;"><a href="javascript:;" onclick="showHtmlTag();" style="color:#0026ff;">插入数据</a>&nbsp;&nbsp;<a href="javascript:;" onclick="showPathSelect();" style="color:#0026ff;">插入库文件</a></div>';
				}
				html+='<textarea id="content" name="content" class="autoNumber" style="width:98%;height:540px;">' + json.value + '</textarea>';
				layer.open({
					type: 1 //此处以iframe举例
					,title: name
					//,skin: 'layui-layer-molv' //加上边框 layui-layer-rim  layui-layer-lan layui-layer-molv layer-ext-moon
					,shadeClose: false //点击遮罩关闭层
					, area: ['90%', '90%']
					,shade: 0.2 //透明度
					,maxmin: false
					,resize: false
					,btnAlign: 'l' //lcr
					,moveType: 0 //拖拽模式，0或者1
					,anim: 0 //0-6的动画形式，-1不开启
					,content: html
					,btn: ['保存修改','关闭'] //只是为了演示
					,yes: function(index,layero)
					{ 

						//var value=$("#content").val().replace(/\r/ig,"").replace(/\n/ig,"0x\\r\\n");
						var value=$("#content").val().encode();
						//url = "?" +  (typeof (AppItem) == "string" && AppItem.length > 0 ? "AppItem=" + AppItem : "ModelID=" + ModelID)  + "&act=save" + (path.length>0 ? "&path=" + path : "") + "&name=" + name;
						url = "?";
						if (typeof (AppItem) == "string" && AppItem.length > 0) {
							url += "AppItem=" + AppItem + "&";
						}
						else {
							if (typeof (ModelID) == "string" && ModelID.length > 0) {
								url += "ModelID=" + ModelID + "&";
							}
						}
						url += "act=save" + (path.length>0 ? "&path=" + path : "") + "&name=" + name;
						$.ajax({
							type: "post", 
							async: true,
							data:{value:value},
							url: url,
							dataType: "json",
							success: function (data) {
								layer.msg(data.message);
								//layer.close(index); 不关闭、继续修改
							},
							error: function (XMLHttpRequest, textStatus, errorThrown) {				
							}
						});
					}	
					,cancel: function(index, layero)
					{
						//layer.msg("X关闭!");
					}
					,success: function(layero, index)
					{
						//alert($('#layui-layer'+ index).height());
						var h=$('#layui-layer'+ index).height()-140;
						var w=$('#layui-layer'+ index).width()-6;
						$("#content").height(h).width(w);
						$("#content").setTextareaCount({width: "40px",bgColor: "#f2f2f2",color: "#000",display: "inline-block"});
						
					}
				});
			}
		}
	});	
};﻿
//文件上传
function fileManage_upload(obj) {
    //var url = "?" +  (typeof (AppItem) == "string" && AppItem.length > 0 ? "AppItem=" + AppItem : "ModelID=" + ModelID)  + "&act=upload" + (path.length > 0 ? "&path=" + path : "");
	var url = "?";
    if (typeof (AppItem) == "string" && AppItem.length > 0) {
        url += "AppItem=" + AppItem + "&";
    }
    else {
        if (typeof (ModelID) == "string" && ModelID.length > 0) {
            url += "ModelID=" + ModelID + "&";
        }
    }
    url += "act=upload" + (path.length > 0 ? "&path=" + path : "");
    if (obj.files) {
        var formData = new FormData();
        for (var i = 0; i < obj.files.length; i++) {
            formData.append('files', obj.files[i], obj.files[i].name);
        }
        $(obj).hide();
        $.ajax({
            type: "POST",
            async: true,
            data: formData,
            url: url,
            contentType: false,
            //dataType: "formData",
            cache: false,//上传文件无需缓存
            processData: false,//用于对data参数进行序列化处理 这里必须false
            dataType: "html",
            success: function (data) {
                // alert(JSON.stringify(data));
                //$(".filemanage_files .clear").before(data);
                $("#filemanage_files").children().last().before(data);
                obj.value = "";
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            }
        });
        $(obj).show();



    }
    else {       
        $.ajaxFileUpload({
            type: "post",
            url: url, //用于文件上传的服务器端请求地址 
            secureuri: false, //一般设置为false 
            fileElementId: $(obj).attr("id"), //文件上传空间的id属性  <input type="file" id="file" name="file" /> 
            dataType: "html", //返回值类型 一般设置为json 		
            complete:function(){},
            success: function (data, status)  //服务器成功响应处理函数
            {
                //$(".filemanage_files .clear").before(data);
                $("#filemanage_files").children().last().before(data);
            },
            error: function (data, status, e)//服务器响应失败处理函数
            {
            }
        });
    }
};
//创建文件
function addFile()
{
	layer.prompt({ title: '输入文件名称', formType: 3, value: '' }, function (value, index) {
		//var url ="?" + (typeof(AppItem)=="string" && AppItem.length > 0 ? "AppItem=" + AppItem  : "ModelID=" + ModelID ) + "&act=addfile" + (path.length>0 ? "&path=" + path : "") + "&name=" + value;
		var url ="?";
		if(typeof(AppItem)=="string" && AppItem.length > 0)
		{
			url+="AppItem=" + AppItem + "&";
		}
		else
		{
			if(typeof(ModelID)=="string" && ModelID.length > 0)
			{
				url+="ModelID=" + ModelID + "&";
			}
		}
		url+= "act=addfile" + (path.length>0 ? "&path=" + path : "") + "&name=" + value;
        layer.close(index);
        document.location.href = url;
    });
};
//创建文件夹
function addFolder()
{
	layer.prompt({ title: '输入文件夹名称', formType: 3, value: name }, function (value, index) {
		//var url = "?" +  (typeof(AppItem)=="string" && AppItem.length > 0 ? "AppItem=" + AppItem  : "ModelID=" + ModelID ) + "&act=addfolder" + (path.length>0 ? "&path=" + path : "") + "&name=" + value;
		var url ="?";
		if(typeof(AppItem)=="string" && AppItem.length > 0)
		{
			url+="AppItem=" + AppItem + "&";
		}
		else
		{
			if(typeof(ModelID)=="string" && ModelID.length > 0)
			{
				url+="ModelID=" + ModelID + "&";
			}
		}
		url+= "act=addfolder" + (path.length>0 ? "&path=" + path : "") + "&name=" + value;
        layer.close(index);
        document.location.href = url;
    });
};
//重命名文件、文件夹
function ReName(name,type)
{
	layer.prompt({ title: '输入文件' + (type == 1 ? '夹' : '') + '名称', formType: 3, value: name }, function (value, index) {
    	//var url = "?" +  (typeof(AppItem)=="string" && AppItem.length > 0 ? "AppItem=" + AppItem  : "ModelID=" + ModelID )+ "&act=rename" + (path.length>0 ? "&path=" + path : "") + "&type=" + type + "&oldname=" + name + "&newname=" + value;
		var url ="?";
		if(typeof(AppItem)=="string" && AppItem.length > 0)
		{
			url+="AppItem=" + AppItem + "&";
		}
		else
		{
			if(typeof(ModelID)=="string" && ModelID.length > 0)
			{
				url+="ModelID=" + ModelID + "&";
			}
		}
		url+= "act=rename" + (path.length>0 ? "&path=" + path : "") + "&type=" + type + "&oldname=" + name + "&newname=" + value;
        layer.close(index);
        document.location.href = url;
    });
};



//auto-line-number.js
;(function($){
	var AutoRowsNumbers = function (element, config){
	    this.$element = $(element);
	    this.$group = $('<div/>', { 'class': "textarea-group" });
	    this.$ol = $('<div/>', { 'class': 'textarea-rows' });
	    this.$wrap = $('<div/>', { 'class': 'textarea-wrap' });
	    this.$group.css({
	    	"width" : this.$element.outerWidth(true) + 'px',
	    	"display" : config.display
	    });
	    this.$ol.css({
	    	"color" : config.color,
	    	"width" : config.width,
	    	"height" : this.$element.height(),
	    	"font-size" : this.$element.css("font-size"),
	    	"line-height" : this.$element.css("line-height"),
	    	"position" : "absolute",
	    	"overflow" : "hidden",
	    	"margin" : 0,
	    	"padding" : 0,
	    	"text-align": "center",
	    	"font-family": "仿宋"
	    });
	    this.$wrap.css({
	    	"padding" : ((this.$element.outerHeight() - this.$element.height())/2) + 'px 0',
	    	"background-color" : config.bgColor,
	    	"position" : "absolute",
	    	"width" : config.width,
	    	"height" : this.$element.height() + 'px'
	    });
	    this.$element.css({
	    	"white-space" : "pre",
	    	"resize": "none",
	    	"margin-left" : (parseInt(config.width) -  parseInt(this.$element.css("border-left-width"))) + 'px',
	    	"width": (this.$element.width() - parseInt(config.width)) + 'px'
	    });

	}

	AutoRowsNumbers.prototype = {
		constructor: AutoRowsNumbers,

		init : function(){
			var that = this;
			that.$element.wrap(that.$group);
			that.$ol.insertBefore(that.$element);
			this.$ol.wrap(that.$wrap)
			that.$element.on('keydown',{ that: that }, that.inputText);
			that.$element.on('scroll',{ that: that },that.syncScroll);
			that.inputText({data:{that:that}});
		},

		inputText: function(event){
			var that = event.data.that;

			setTimeout(function(){
				var value = that.$element.val();
				value.match(/\n/g) ? that.updateLine(value.match(/\n/g).length+1) : that.updateLine(1);
				that.syncScroll({data:{that:that}});
			},0);
		},

		updateLine: function(count){
			var that = this;
			that.$element;
			that.$ol.html('');

			for(var i=1;i<=count;i++){
				that.$ol.append("<div>"+i+"</div>");
			}
		},

		syncScroll: function(event){
			var that = event.data.that;
			that.$ol.children().eq(0).css("margin-top",  -(that.$element.scrollTop()) + "px");
		}
	}

	$.fn.setTextareaCount = function(option){
		var config = {};
		var option = arguments[0] ? arguments[0] : {};
		config.color = option.color ? option.color : "#FFF";
		config.width = option.width ? option.width : "30px";
		config.bgColor = option.bgColor ? option.bgColor : "#999";
		config.display = option.display ? option.display : "block";

	    return this.each(function () {
	      var $this = $(this),
	          data = $this.data('autoRowsNumbers');

	      if (!data){ $this.data('autoRowsNumbers', (data = new AutoRowsNumbers($this, config))); }
	      
		  if (typeof option === 'string'){
	        return false;
	      } else {
	        data.init();
	      }
	    });
	}
})(jQuery);

//drag-arrange.js

//alert(virtualPath);
if(typeof(virtualPath)!="undefined")
{
	//﻿document.write('<script src="' + virtualPath + 'Scripts/ajaxfileupload.js"><\/script>');
}
function eImages_setjson(pbody)
{
		var json='[';
		pbody.find("div").each(function(index, element){
			if(index>0){json+=',';}
			json+='{"url":"' + $(this).attr("url") + '"}';
        });
		json+=']';
		//var elements=pbody.find("input,textarea");
		//alert(elements[0].tagName);
		var txtid=pbody.attr("id").replace("_body","");
		pbody.find("#" + txtid).val(json);
		return;
		
		if(json.length>2)
		{
			//pbody.find("input:eq(0)").val(json);
			//pbody.find("textarea:eq(0)").val(json);
		}
		else
		{
			//pbody.find("input:eq(0)").val("");
			//pbody.find("textarea:eq(0)").val("");
		}
};
function checkext(path)
{
	var exts=".gif.jpg.jpeg.png.bmp.tif";
	var arr=path.toLowerCase().split(".");
	var ext="." + arr[arr.length-1];	
	if(exts.indexOf(ext)>-1)
	{
		return true;
	}
	else
	{
		return false;
	}
};
function eImage_change(obj)
{
	var url=$(obj).parent().attr("vpath") + "Plugins/ProUpload.aspx?type=image";	
	if($(obj).parent().attr("MaxWidth").length>1) {url+="&PictureMaxWidth=" + $(obj).parent().attr("MaxWidth");}
	if(obj.files)
	{
		var formData = new FormData();
		for(var i=0;i<obj.files.length;i++)
		{
			if(!checkext(obj.files[i].name))
			{
				alert("文件类型不支持,只支持以下格式\n(jpg|jpeg|gif|bmp|png|tif)");
				obj.value="";
				return;
			}
			formData.append('files', obj.files[i], obj.files[i].name);
		}
		$(obj).hide();
		$.ajax({
            type: "POST", async: true,
			data:formData,
            url: url,
            dataType: "json",
			contentType: false,
			//dataType: "formData",
			cache: false,//上传文件无需缓存
            processData: false,//用于对data参数进行序列化处理 这里必须false
            success: function (data) 
			{
				if(data.files.length>0)
				{
					$("#" + $(obj).attr("id").replace("_file","")).val(data.files[0].url);
					$(obj).parent().css("background-image","url(" + data.files[0].url  + ")");
				}
				obj.value="";			
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {}
        });
		$(obj).show();		
	}
	else
	{
		alert("当前浏览器版本低!");
	}	
};
function eImages_change(obj)
{
	//var form = new FormData(obj.parentNode);
	//alert(FormData);
	//alert(eImages_setjson);
	//return;
	//alert(formData);
	//return;
	var _back=true;
	var url=$(obj).parent().parent().attr("vpath") + "Plugins/ProUpload.aspx?type=image&ThumbWidth=120";	
	if($(obj).parent().parent().attr("MaxWidth").length>1) {url+="&PictureMaxWidth=" + $(obj).parent().parent().attr("MaxWidth");}

	if(obj.files)
	{
		var formData = new FormData();
		for(var i=0;i<obj.files.length;i++)
		{
			if(!checkext(obj.files[i].name))
			{
				alert("文件类型不支持,只支持以下格式\n(jpg|jpeg|gif|bmp|png|tif)");
				obj.value="";
				return;
			}
			formData.append('files', obj.files[i], obj.files[i].name);
		}
		
		$(obj).hide();
		$.ajax({
            type: "POST", async: true,
			data:formData,
            url: url,
            dataType: "json",
			contentType: false,
			//dataType: "formData",
			cache: false,//上传文件无需缓存
            processData: false,//用于对data参数进行序列化处理 这里必须false
            success: function (data) 
			{
				for(var i=0;i < data.files.length; i++)
				{					
					$(obj).parent().before('<div onclick="viewImage(\'' +  data.files[i].url.replace("_thumb","") + '\',800,600);" url="' + data.files[i].url + '" style="background-image:url(' + data.files[i].url + ');"><img src="'+ $(obj).parent().parent().attr("vpath") +'images/none.gif" /></div>');					
				}
				var pbody=$(obj).parent().parent();
				
				pbody.find("div").arrangeable();
				obj.value="";
				eImages_setjson(pbody);
				
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {}
        });
		$(obj).show();
		
		
	}
	else
	{
		_back=checkext(obj.value);
		if(!_back)
		{
			alert("文件类型不支持,只支持以下格式\n(jpg|jpeg|gif|bmp|png|tif)");
			obj.value="";
			return;
		}

		
		 $.ajaxFileUpload ({
						   type: "post",
						   url: url, //用于文件上传的服务器端请求地址 
						   secureuri: false, //一般设置为false 
						   fileElementId: $(obj).attr("id"), //文件上传空间的id属性  <input type="file" id="file" name="file" /> 
						   dataType: "json", //返回值类型 一般设置为json 
						   success: function (data, status)  //服务器成功响应处理函数
                		   {
							  
							   for(var i=0;i < data.files.length; i++)
							   {
								   //alert(data.files[i].url.replace("_thumb",""));
									$(obj).parent().before('<div onclick="viewImage(\'' +  data.files[i].url.replace("_thumb","") + '\',800,600);" url="' + data.files[i].url + '" style="background-image:url(' + data.files[i].url + ');"><img src="'+ $(obj).attr("vpath") +'images/none.gif" /></div>');					
								}
								var pbody=$(obj).parent().parent();								
								pbody.find("div").arrangeable();
								obj.value="";
								eImages_setjson(pbody);
						   }, 
						   error: function (data, status, e)//服务器响应失败处理函数
                		   {
								//alert(e); 
						   } 
				});		 
	}
};
'use strict';
(function (factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['jquery'], factory);
  } else {
    // Browser globals
    factory(jQuery);
  }
}(function ($) {
  var IS_TOUCH_DEVICE = ('ontouchstart' in document.documentElement);
  /**
   * mouse move threshold (in px) until drag action starts
   * @type {Number}
   */
  var DRAG_THRESHOLD = 5;
  /**
   * to generate event namespace
   * @type {Number}
   */
  var counter = 0;

  /**
   * Javascript events for touch device/desktop
   * @return {Object}
   */
  var dragEvents = (function () {
    if (IS_TOUCH_DEVICE) {
      return {
        START: 'touchstart',
        MOVE: 'touchmove',
        END: 'touchend'
      };
    }
    else {
      return {
        START: 'mousedown',
        MOVE: 'mousemove',
        END: 'mouseup'
      };
    }
  }());

  $.fn.arrangeable = function(options) {
	var t=null;
    var dragging = false;
    var $clone;
    var dragElement;
    var originalClientX, originalClientY; // client(X|Y) position before drag starts
    var $elements;                        // list of elements to shift between
    var touchDown = false;
    var leftOffset, topOffset;
    var eventNamespace;

    if (typeof options === "string") {
      // check if want to destroy drag-arrange
      if (options === 'destroy') {
        if (this.eq(0).data('drag-arrange-destroy')) {
          this.eq(0).data('drag-arrange-destroy')();
        }

        return this;
      }
    }

    options = $.extend({
      "dragEndEvent": "drag.end.arrangeable"
    }, options);

    var dragEndEvent = options["dragEndEvent"];

    $elements = this;
    eventNamespace = getEventNamespace();

    this.each(function() {

      // bindings to trigger drag on element
	  
      var dragSelector = options.dragSelector;
      var self = this;
      var $this = $(this);
	  var $body= $this.parent();
	  if($body.attr("class")=="efiles-body")
	  {
		$(this).unbind().mouseover(function (){ $this.find("img").show(); }).mouseout(function () { $this.find("img").hide(); });
	  }
	  if($body.attr("class")=="efiles-body")
	  {
		 $this.find("img").unbind().click(function (e) {
			e.stopPropagation();
			var _back=confirm('确认要删除吗？');
			if(!_back){return;};
			var $div=$(this).parent();
			var $url=$div.attr("url");
			if($url.toLowerCase().indexOf("/temp/") > -1)
			{
				var url=$div.parent().attr("vpath") + "Plugins/ProUpload.aspx?act=del&file=" + $url;			
				$.ajax({
					type: "GET", async: true,
					url: url,
					dataType: "html",
					success: function (data) {}
				});		
			}
			$this.remove();
			eImages_setjson($body);
		});
	  }


      if (dragSelector) {
        $this.on(dragEvents.START + eventNamespace, dragSelector, dragStartHandler);
      } else {
        $this.on(dragEvents.START + eventNamespace, dragStartHandler);
      }
	  self.onmouseup=function(e)
	  {
		  clearInterval(t);
		  dragging=false;
		  touchDown=false;
		  dragElement.style.cursor="pointer";
	  };
	  var draw=function(){
		  clearInterval(t);		 
		  touchDown=true;
		  dragElement.style.cursor="move";
	  };	
      function dragStartHandler(e) {
        // a mouse down/touchstart event, but still drag doesn't start till threshold reaches
        // stopPropagation is compulsory, otherwise touchmove fires only once (android < 4 issue)
        e.stopPropagation();
		var src=e.srcElement||e.target;
		if(src.tagName=="TEXTAREA"){return;}
		t=setInterval(draw,350);
		
        //touchDown = true;
		//document.title="true";
        originalClientX = e.clientX || e.originalEvent.touches[0].clientX;
        originalClientY = e.clientY || e.originalEvent.touches[0].clientY;
        dragElement = self;
      }
    });

    // bind mouse-move/touchmove on document
    // (as it is not compulsory that event will trigger on dragging element)
    $(document).off().on(dragEvents.MOVE + eventNamespace, dragMoveHandler)
      .on(dragEvents.END + eventNamespace, dragEndHandler);

    function dragMoveHandler(e) {		
      if (!touchDown) { return; }
      var $dragElement = $(dragElement);
      var dragDistanceX = (e.clientX  || e.originalEvent.touches[0].clientX) - originalClientX;
      var dragDistanceY = (e.clientY || e.originalEvent.touches[0].clientY) - originalClientY;

      if (dragging) {
        e.stopPropagation();

        $clone.css({
          left: leftOffset + dragDistanceX,
          top: topOffset + dragDistanceY
        });

        shiftHoveredElement($clone, $dragElement, $elements);

      // check for drag threshold (drag has not started yet)
      } else if (Math.abs(dragDistanceX) > DRAG_THRESHOLD ||
          Math.abs(dragDistanceY) > DRAG_THRESHOLD) {
        $clone = clone($dragElement);

        // initialize left offset and top offset
        // will be used in successive calls of this function
        leftOffset = dragElement.offsetLeft - parseInt($dragElement.css('margin-left')) - 
          parseInt($dragElement.css('padding-left'));
        topOffset = dragElement.offsetTop - parseInt($dragElement.css('margin-top')) - 
          parseInt($dragElement.css('padding-top'));

        // put cloned element just above the dragged element
        // and move it instead of original element
        $clone.css({
          left: leftOffset,
          top: topOffset
        });
        $dragElement.parent().append($clone);

        // hide original dragged element
        $dragElement.css('visibility', 'hidden');

        dragging = true;
		//document.title+="DD";
      }
    };
	
    function dragEndHandler(e) {
		//document.title+=dragging;
      if (dragging) {
        // remove the cloned dragged element and
        // show original element back
        e.stopPropagation();
        dragging = false;
        $clone.remove();
        dragElement.style.visibility = 'visible';

        $(dragElement).parent().trigger(dragEndEvent, [$(dragElement)]);
		

		//document.title=$(dragElement).html();//.parent().attr("callback");

		if($(dragElement).parent().attr("callback")=="eImages_setjson")
		{
			eImages_setjson($(dragElement).parent());
		}
		else if($(dragElement).parent().parent().attr("callback")=="eediter_setjson")
		{
			eediter_setjson($(dragElement).parent());
		}
		else
		{
			if(options.dragEnd !== undefined)
			{
				if(typeof options.dragEnd === "function"){options.dragEnd(dragElement);}
				else{eval(options.dragEnd + '(' + dragElement + ');');}
			}
		}
      }
      touchDown = false;
    };

    function destroy() {
      $elements.each(function() {
        // bindings to trigger drag on element
        var dragSelector = options.dragSelector;
        var $this = $(this);

        if (dragSelector) {
          $this.off(dragEvents.START + eventNamespace, dragSelector);
        } else {
          $this.off(dragEvents.START + eventNamespace);
        }
      });

      $(document).off(dragEvents.MOVE + eventNamespace)
        .off(dragEvents.END + eventNamespace);

      // remove data
      $elements.eq(0).data('drag-arrange-destroy', null);

      // clear variables
      $elements = null;
      dragMoveHandler = null;
      dragEndHandler = null;
    }

    this.eq(0).data('drag-arrange-destroy', destroy);
  };

  function clone($element) {
    var $clone = $element.clone();

    $clone.css({
      position: 'absolute',
      width: $element.width(),
      height: $element.height(),
      'z-index': 100000 // very high value to prevent it to hide below other element(s)
    });

    return $clone;
  };

  /**
   * find the element on which the dragged element is hovering
   * @return {DOM Object} hovered element
   */
  function getHoveredElement($clone, $dragElement, $movableElements) {
    var cloneOffset = $clone.offset();
    var cloneWidth = $clone.width();
    var cloneHeight = $clone.height();
    var cloneLeftPosition = cloneOffset.left;
    var cloneRightPosition = cloneOffset.left + cloneWidth;
    var cloneTopPosition = cloneOffset.top;
    var cloneBottomPosition = cloneOffset.top + cloneHeight;
    var $currentElement;
    var horizontalMidPosition, verticalMidPosition;
    var offset, overlappingX, overlappingY, inRange;

    for (var i = 0; i < $movableElements.length; i++) {
      $currentElement = $movableElements.eq(i);

      if ($currentElement[0] === $dragElement[0]) { continue; }

      offset = $currentElement.offset();

      // current element width and draggable element(clone) width or height can be different
      horizontalMidPosition = offset.left + 0.5 * $currentElement.width();
      verticalMidPosition = offset.top + 0.5 * $currentElement.height();

      // check if this element position is overlapping with dragged element
      overlappingX = (horizontalMidPosition < cloneRightPosition) &&
        (horizontalMidPosition > cloneLeftPosition);

      overlappingY = (verticalMidPosition < cloneBottomPosition) &&
        (verticalMidPosition > cloneTopPosition);

      inRange = overlappingX && overlappingY;

      if (inRange) {
        return $currentElement[0];
      }
    }
  };

  function shiftHoveredElement($clone, $dragElement, $movableElements) {
    var hoveredElement = getHoveredElement($clone, $dragElement, $movableElements);

    if (hoveredElement !== $dragElement[0]) {
      // shift all other elements to make space for the dragged element
      var hoveredElementIndex = $movableElements.index(hoveredElement);
      var dragElementIndex = $movableElements.index($dragElement);
      if (hoveredElementIndex < dragElementIndex) {
        $(hoveredElement).before($dragElement);
      } else {
        $(hoveredElement).after($dragElement);
      }

      // since elements order have changed, need to change order in jQuery Object too
      shiftElementPosition($movableElements, dragElementIndex, hoveredElementIndex);
    }
  };

  function shiftElementPosition(arr, fromIndex, toIndex) {
    var temp = arr.splice(fromIndex, 1)[0];
    return arr.splice(toIndex, 0, temp);
  };

  function getEventNamespace() {
    counter += 1;

    return '.drag-arrange-' + counter;
  };

}));

//子窗口关闭自己
function eFrameTab_close()
{
	 if (self != top) {
            $("iframe", window.parent.document).each(function () {
                if (this.contentWindow.document == self.document) {
                    top.eFrameTab_remove($(this).index());
                }
            });
        }
};
function eFrameTab_add(url,text)
{
	var _href=url.getquerystring("appitem").length > 0 ?   url.getquerystring("appitem") : url;
		//var tab = $(".eFrameTab dt a[_href='" + url + "']");
        var tab = $(".eFrameTab dt a[_href='" + _href + "']");
		var txtlen= $(".eFrameTab dt a:contains('" + text + "')");
		
        if (tab.length == 0 || txtlen.length==0) {
			//$(".eFrameTab dt").append('<a href="javascript:;" _href="' + url + '" onclick="this.blur();"><span title="' + text + '">' + text + '</span><em></em></a>');
            $(".eFrameTab dt").append('<a href="javascript:;" _href="' + _href + '" onclick="this.blur();"><span title="' + text + '">' + text + '</span><em></em></a>');			
            $(".eFrameTab dd").append('<iframe scrolling="auto" frameborder="0" src="' + url + '"></iframe>');
            eFrameTab_show($(".eFrameTab dt a").length - 1);
        }
        else
        {
            var index = tab.index();
            eFrameTab_show(index);
            $(".eFrameTab dd iframe:eq(" + index + ")").attr("src",url);
        }
};
    function eFrameTab_remove(index)
    {
        if (index == 0) { return; }
        var tab = $(".eFrameTab dt a:eq(" + index + ")");
        var curtab = $(".eFrameTab dt a.cur");
        var _index = -1;
        if (tab.index() == curtab.index())
        {
            var len = $(".eFrameTab dt a").length;
            _index = len == 2 ? 0 : index - 1;
        }
        $(".eFrameTab dt a:eq(" + index + ")").remove();
        $(".eFrameTab dd iframe:eq(" + index + ")").remove();
        eFrameTab_show(_index);
    };
    function eFrameTab_show(index)
    {
        if (index<0) { return; }
        var $a = $(".eFrameTab dt a:eq(" + index + ")");
        if ($a.hasClass("cur")) { return; }

        $(".eFrameTab dt a.cur").removeClass("cur");
        $(".eFrameTab dt a:eq(" + index + ")").addClass("cur");
        $(".eFrameTab dd iframe:visible").hide();
        $(".eFrameTab dd iframe:eq(" + index + ")").show();
    };
function eFrameTab_Init()
{
	$(".eFrameTab dd").css("height", ($(".eFrameTab").parent().height() - $(".eFrameTab dt").outerHeight()) + "px");
	$(".eFrameTab dt").click(function (e) {
            var evt = e || window.event;
            var src = evt.srcElement || evt.target;
            evt.preventDefault();
            var $a = src.tagName == "A" ? $(src) : $(src).parents("a:first");
            if (src.tagName == "DT") { return; }
            if (src.tagName == "EM") {
                var index = $a.index();
                eFrameTab_remove(index);
                return;
            }
            eFrameTab_show($a.index());
        });
        $(".eFrameTab dt").dblclick(function (e) {

            var evt = e || window.event;
            var src = evt.srcElement || evt.target;
            var $a = src.tagName == "A" ? $(src) : $(src).parents("a:first");
            if (src.tagName == "DT") { return; }
            var index = $a.index();
            eFrameTab_remove(index);
        });
	
};
function department_delete(obj)
{	
	var src = getsrcElement(); 
	if(src.tagName!="IMG"){return;}
	var box=$(obj).parents("span:first");
	var ctrlname=box.attr("id").replace("_box","");
	box.find("[postname='" + ctrlname + "']").val("");
	box.find("[postname='" + ctrlname + "_text']").val("");
	$(obj).parent().remove();
};
function multipleuser_delete(obj)
{
	var src = getsrcElement(); 
	if(src.tagName!="IMG"){return;}
	//$(obj).parent().remove();
	var box=$(obj).parents("span:first");
	var ctrlname=box.attr("id").replace("_box","");
	if(box.attr("etype")=="singleuser")
	{
		box.find("[postname='" + ctrlname + "']").val("");
		box.find("[postname='" + ctrlname + "_text']").val("");
		$(obj).parent().remove();
	}
	else
	{
		var ovalue=box.find("[postname='" + ctrlname + "']").val();		
		var idx=$(obj).parent().index()-2;//去掉value和text两个
		var arr=ovalue.split(",");
		var nvalue="";
		var ntext="";
		for(var i=0;i<arr.length;i++)
		{
			if(idx==i){continue;}
			if(nvalue.length>0){nvalue+=",";ntext+=",";}
			nvalue+=arr[i];
			ntext+=box.find(".useritem:eq(" + i + ") p").html();
		}
		box.find("[postname='" + ctrlname + "']").val(nvalue);
		box.find("[postname='" + ctrlname + "_text']").val(ntext);
		$(obj).parent().remove();
	}
};
if(window.addEventListener){window.addEventListener("load",eFrameTab_Init, false);}else{window.attachEvent("onload",eFrameTab_Init);}